[英]Why does `type(myField)` return `<type 'instance'>` and not `<type 'Field'>`?
I am confronted to a python problem.我遇到了 python 问题。 I want to use type()
to find out what type of variable I am using.我想使用type()
来找出我正在使用的变量类型。 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.编辑: myField() 是我定义的 class 。
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.当我要求 type() 时,我得到: <type 'instance'>
现在根据1 ,这是因为我使用了 class 元素并要求type()
。 Now what I need is: <type 'int'>
for the example: myField(42)
and <type 'str'>
for myField(foo)
.现在我需要的是: <type 'int'>
为示例: myField(42)
和<type 'str'>
为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.代码取自 scapy,我尝试对其进行调整。
in python 2, all of your classes should inherit from object
.在 python 2 中,您的所有类都应继承自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
.如果你不这样做,你最终会得到“旧样式类”,它们总是类型为classobj
,并且其实例总是类型为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()
:如果您需要检查旧式 class 的类型,您可以使用它的__class__
属性,或者更好的是,使用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?但是...您想知道传递给 class 构造函数的参数类型吗? well, that's a bit out of python's hands.好吧,这有点超出了python的掌控。 You'll have to know just what your class does with it's arguments.您必须知道 class 与 arguments 的作用。
You are placing myField instances into an array.您正在将 myField 实例放入数组中。 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.如果您想获得 int 或 str 类型,则需要访问 myField 实例中的该字段。
def returnArr(self):
for i in self.array:
print type(i.accessor)
i will then be your myField and you should be able to access the int or str with an accessor.然后,我将成为您的 myField,您应该能够使用访问器访问 int 或 str。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.