此代碼在Python 2
和Python 3
中產生不同的輸出。Python描述符無法在Python 2.7中工作
class Descriptor(object):
def __get__(self, instance, owner):
print('read')
return 1
def __set__(self, instance, value):
print('write')
def __delete__(self, instance):
print('del')
class C():
a = Descriptor()
c = C()
c.a
c.a = 3
del c.a
c.a
print('finished')
爲Python 2的輸出是:
read
read
finished
對於Python 3是:
read
write
del
read
finished
這是爲什麼以這種方式工作? Python 2
描述符與Python 3
描述符有什麼不同?
這也沒有什麼意義,因爲http://docs.python.org/release/3.0.1/reference/datamodel.html#invoking-descriptors清楚地描述完全一樣 http://docs.python.org/reference/datamodel.html#invoking-descriptors
(這些是Python 2.7
和Python 3.0
本細則。)
(順便說一句,Python的3.0和它的文檔是過時的和退休的;不要使用Python 3.0或3.0.1當前文檔是在http://文檔。 python.org/py3k/和當前版本是3.2.3) –