使用描述符管理属性:
class Geeks:
def __init__(self,value):
self.age = value
def __getattribute__(self,attr):
return object.__getattribute__(self,attr)
def __setattr__(self,attr,value):
return object.__setattr__(self, attr,value)
初始化具有真实属性age
10的Geeks
类:
boy = Geeks(10)
boy.age
10
boy.__dict__
{ age : 10}
The instance boy
contains a real attribute age
.
In almost every book,use property
class to mange the age
attribute(some in the form of self.__age
or self.age_
or self._age
,it does not matter):
class Geeks:
def __init__(self,value):
self._age = value
def get_age(self):
return self._age
def set_age(self, value):
self._age = value
age = property(get_age, set_age)
显示属性:
boy = Geeks(10)
boy.age
10
boy.__dict__
{ _age : 10}
真实属性是_age
,而不是age
。_age
age属性(get_age,set_age)创建真实的age
属性时,我遇到了RecursionError
。
class Geeks:
def __init__(self,value):
self.age = value
def get_age(self):
return self.age
def set_age(self, value):
return self.age = value
age = property(get_age, set_age)
相同错误:
class Geeks:
def __init__(self,value):
self.age = value
def get_age(self):
return object.__getattribute__(self, age )
def set_age(self, value):
object.__setattr__(self, age ,value)
age = property(get_age, set_age)
如何使属性(get_age,set_age)
创建真正的属性age
,而不是_age
或类似的属性?