class Student():
def __init__(self,name,score):
self.__name = name
self.__score = score
@property
def name(self):
return self.__name
@name.setter
def name(self,name):
self.__name = name
s1 = Student(‘zhang‘,25)
print(s1.name) #s1.name就相当于执行了s1.get_name()
s1.name = ‘wang‘ #s1.name = ‘wang‘就相当于执行了s1.set_name(‘wang‘)
print(s1.name)
这两个装饰器的意义在于,简化操作,能够像操作普通属性一样操作一些方法,方法内容正常些,方法名就定义为属性名,在方法前加装饰器@property就把这个方法变成了读取值方法(get),在方法前加装饰器"@属性名.setter"就将其定义为了赋值方法(set)
原文地址:https://www.cnblogs.com/zhangzhaoyu/p/9235252.html
时间: 2024-10-16 00:11:25