在这个例子中的代码,我想,以确定是否x
是TestProperty
一个实例:如何确定描述符的类?
class TestProperty(object):
def __init__(self, name):
self._name = name
def __get__(self, instance, cls):
return getattr(instance, self._name)
def __set_(self, instance, value):
setattr(instance, self._name, value)
class Test(object):
x = TestProperty("x")
print isinstance(Test.x, TestProperty)
不过,我得到以下异常:
Traceback (most recent call last):
File "/home/zenoss/testproperties.py", line 14, in <module>
print isinstance(Test.x, TestProperty)
File "/home/zenoss/testproperties.py", line 6, in __get__
return getattr(instance, self._name)
AttributeError: 'NoneType' object has no attribute 'x'
反正是有说,如果一个属性当它是一个描述符时,它是一个类的实例吗?
谢谢,当'实例是None'时返回'self'会有诀窍。 – Ben
@本,不客气。快乐的Python黑客! – falsetru