以代码示例的方法介绍@property属性
使用@property属性
class Boy(object):
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
self._name = new_name
@name.deleter
def name(self):
del self._name
if __name__ == "__main__":
boy = Boy('Tom')
print(boy.name)
boy.name = 'Alice'
print(boy.name)
del boy.name
print(boy.name)
不使用@property属性
class Boy(object):
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
def set_name(self, new_name):
self.name = new_name
def del_name(self):
del self.name
if __name__ == "__main__":
boy = Boy('Tom')
print(boy.get_name())
boy.set_name('Alice')
print(boy.get_name())
boy.del_name()
print(boy.get_name())
|