Python中装饰属性的方法

1、使用 get、set 方法来封装对一个属性的访问在很多面向对象编程的语言中都很常见。

classStudent(object):
def__init__(self,name,score):
self.name=name
self.__score=score

defget_score(self):
returnself.__score

defset_score(self,score):
self.__score=score

s=Student('zhangsan',90)
s.set_score(100)
print(s.get_score())
#输出100

2、Python里提供了@property装饰器,可以把方法“装饰”成属性调用。

classStudent(object):
def__init__(self,name,score):
self.name=name
self.__score=score

@property
defscore(self):
returnself.__score

@score.setter
defscore(self,score):
self.__score=score

s=Student('zhangsan',90)
s.score=100
print(s.score)
#输出100

以上就是Python中装饰属性的方法,希望对大家有所帮助。更多Python学习推荐:python教学

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。