2013-02-21 59 views

回答

2

属性对象本身是Person.__dict__

In [16]: Person.__dict__ 
Out[16]: dict_proxy({'__module__': '__main__', 'age': <property object at 0xa387c0c>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, '__init__': <function __init__ at 0xa4d66f4>}) 

a.age是一个函数调用的返回值。它使用descriptor lookup mechanism拨打Person.__dict__['age'].__get__(a,Person)

Python不会在__dict__中存储{'age':28},因为28不一定是固定值。被调用的函数可能会在每次调用时返回不同的值。因此将'age'与仅一个返回值相关联就没有意义了。

考虑,例如,

class Person(object): 
    def __init__(self): 
     self.count = 0 
    @property 
    def age(self): 
     self.count += 1 
     return self.count  

a = Person() 
print(a.age) 
# 1 
print(a.age) 
# 2 
相关问题