![](/img/trans.png)
[英]What does isinstance mean combined with ScalarNode, SequenceNode, and MappingNode?
[英]isinstance(xxx, property) works, but what does that correspond to in the types module?
我可以使用isinstance来测试一个属性是否是一个属性(实际上是在类上),但是在类型模块中找不到与该属性相对应的任何东西。
希望下面的代码可以使这一点更加清楚。 我正在测试的所有其他内容都能很好地匹配。
class MyClass(object):
def __init__(self):
self._counter = 0
def counter():
doc = "The counter property."
def fget(self):
self._counter +=1
return self._counter
return locals()
counter = property(**counter())
def bar(self):
self
foo = MyClass()
print "foo.counter", foo.counter
print "foo.counter", foo.counter
print "this will be an int. type(foo.counter):", type(foo.counter)
print "but the class knows it's a property isinstance(foo.__class__.counter, property):", isinstance(foo.__class__.counter, property)
#let's see if we can determine the type of a given item...
import types
to_test = [3, foo.__class__.counter, foo.bar, {}]
print "matches against types:"
for k, v in vars(types).items():
for test in to_test[:]:
if type(test) == v:
#flag a match, remove it from tests
print (" %s is a %s" % (test, v))
to_test.remove(test)
#what's left over? the property
print "\n\nno match found... :(", to_test
输出...
foo.counter 1
foo.counter 2
this will be an int. type(foo.counter): <type 'int'>
but the class knows its a property isinstance(foo.__class__.counter, property): True
matches against types:
3 is a <type 'int'>
<bound method MyClass.bar of <__main__.MyClass object at 0x106b06a50>> is a <type 'instancemethod'>
{} is a <type 'dict'>
no match found... :( [<property object at 0x106afc838>]
是什么赋予了? 为什么在任何地方都无法根据类型识别属性?
我很好奇的原因是我有一个调试功能,试图漂亮地打印复杂的对象。 我很久以前就了解到,在这些对象上调用方法不是一个好主意。 因此,我传入了一个默认的属性类型列表,以供查看。
li_skiptype=[types.MethodType]
几乎所有时间,我都会跳过方法,但是如果我从列表中删除它们,我可以很好地打印它们。 添加它会很好 并让我跳过属性类型也是有条件的。
好吧...我只是很好奇为什么它们没有类型。
types
并不意味着是所有Python对象类型的全面集合。 从模块文档中 :
此模块为标准Python解释器使用的某些对象类型定义名称,但不为各种扩展模块定义的类型定义名称。
强调我的。
模块中的大多数对象只是内置类型的别名,请参见模块源代码 ; 这里的类型对象没有什么神奇的东西; 它们只是更多的Python对象,而其中的一些对象不容易公开。 然后,该模块只是一个方便。
您已经具有要测试的property
对象,并且在types
模块中也不需要引用该对象。
在Python 3中, types
模块已进一步缩小为一组有限的类型,否则这些类型可能很难获得引用。 已删除的类型是可以直接以内置方式直接使用的类型。 再次引用Python 2文档:
从Python 2.2开始,内置的工厂函数(例如
int()
和str()
也是相应类型的名称。 现在,这是访问类型的首选方法,而不是使用类型模块。
由于property
是从一开始就作为内置语言添加到语言中的,因此您无需直接以types
公开该property
。
请注意,使用isinstance()
几乎总是更好,并允许使用子类。 如果必须限制测试只有一个类型,使用的is
作为一个类型单身; 使用type(obj) is sometype
而不是type(obj) == sometype
。 另请参阅Python样式指南 :
对象类型比较应始终使用
isinstance()
而不是直接比较类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.