在這個例子中的代碼,我想,以確定是否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