Skip to content Skip to sidebar Skip to footer

Why Does `type(myfield)` Return `` And Not ``?

I am confronted to a python problem. I want to use type() to find out what type of variable I am using. The code looks similar to this one: class Foo(): array=[ myField(23

Solution 1:

in python 2, all of your classes should inherit from object. If you don't, you end up with "old style classes", which are always of type classobj, and whose instances are always of type instance.

>>>classmyField():...pass...>>>classyourField(object):...pass...>>>m = myField()>>>y = yourField()>>>type(m)
<type 'instance'>
>>>type(y)
<class '__main__.yourField'>
>>>

If you need to check the type of an old-style class, you can use its __class__ attribute, or even better, use isinstance():

>>> m.__class__
<class__main__.myField at 0xb9cef0>
>>> m.__class__ == myField
True>>> isinstance(m, myField)
True

But... you want to know the type of the argument passed to your class constructor? well, that's a bit out of python's hands. You'll have to know just what your class does with it's arguments.

Solution 2:

You are placing myField instances into an array. That is why the type is instance. If you would like to get the int or str type you will need to access that field in your myField instance.

defreturnArr(self):
   for i in self.array:
       printtype(i.accessor)

i will then be your myField and you should be able to access the int or str with an accessor.

Post a Comment for "Why Does `type(myfield)` Return `` And Not ``?"