Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `type(myField)` return `<type 'instance'>` and not `<type 'Field'>`?

Tags:

python

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),myField(42),myField("foo"), myField("bar")]
       def returnArr(self):
          for i in self.array:
               print type(i)

if __name__ == "__main__":
    a=Foo()
    a.returnArr()

Edit: myField() is a class I defined.

When I ask for the type() I get: <type 'instance'> Now according to 1 this is due to the fact that I use a class element and ask for type() on that. Now what I need is: <type 'int'> for the example: myField(42) and <type 'str'> for myField(foo). How could I acheive that?

EDIT:

def __init__(self, name, default, fmt="H"):
    self.name = name
    if fmt[0] in "@=<>!":
        self.fmt = fmt
    else:
        self.fmt = "!"+fmt
    self.default = self.any2i(None,default)
    self.sz = struct.calcsize(self.fmt)
    self.owners = []

The code is taken from scapy and I try to adapt it.

like image 291
Steve Avatar asked Jul 12 '11 15:07

Steve


1 Answers

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.

>>> class myField():
...     pass
... 
>>> class yourField(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.

like image 183
SingleNegationElimination Avatar answered Oct 26 '22 10:10

SingleNegationElimination