我正在学习python,肯定是一个愚蠢的问题,但我找不到任何答案。
我有一个对象
class ant(object):
def __init__(self, age):
self.age = 0
def update_age(self)
self.age += 1
pebbles = myant(25)
#check age
print pebbles.age
现在我想要做的是每次有人检查pebble.age时,鹅卵石会在内部自动运行update_age()。 有可能吗?或每次我必须检查pebbles_age我必须写:
pebbles.update_age()
print pebbles.age.
非常感谢
答案 0 :(得分:4)
您可以使用property:
实现此目的class Ant(object): # note leading uppercase, per style guide (PEP-8)
def __init__(self): # you ignore the age parameter anyway
self._age = 0
def update_age(self):
self._age += 1
@property
def age(self):
self.update_age()
return self._age
这使age
成为只读,并正确递增:
>>> an_ant = Ant()
>>> an_ant.age
1
>>> an_ant.age
2
>>> an_ant.age = 10
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
an_ant.age = 10
AttributeError: can't set attribute