要訪問描述符對象本身,您需要使用類的__dict__
屬性調用它。
def dump(self):
print type(self).__dict__['a'].describe()
欲瞭解更多關於描述符的信息,請閱讀Descriptor HowTo Guide。
演示:
class MyDescriptor(object):
def __get__(self, obj, type=None):
return self._val
def __set__(self, obj, val):
self._val = val
def describe(self):
return 'inside describe'
class MyClass(object):
a = MyDescriptor()
def __init__(self):
self.a = 42
def dump(self):
print 'Inside dump()'
print self.a.describe()
def dump2(self):
print 'Inside dump2()'
print type(self).__dict__['a'].describe()
MyClass().dump2()
print '-'*20
MyClass().dump()
輸出:
Inside dump2()
inside describe
--------------------
Inside dump()
Traceback (most recent call last):
File "C:\Python27\SO.PY", line 26, in <module>
MyClass().dump()
File "C:\Python27\SO.PY", line 19, in dump
print self.a.describe()
AttributeError: 'int' object has no attribute 'describe'
'self.a.describe()'?請注意,由於您使用的是「類變量」,因此「MyClass」的所有實例都將包含「MyDescriptor」的_same_實例。 –