python装饰属性的方法
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学习推荐:请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python怎么获取列表元素的索引
本文主要介绍了python中如何获取列表的索引,以及如何返回列表中某个值的索引。1、index方法list_a=[12,213,22,2,32]forainlist_a:print(list_a...详情>>
2023-11-10 18:02:55
python模块怎么使用
Python提供了强大的模块支持,主要体现在,不仅Python标准库中包含了大量的模块(称为标准模块),还有大量的第三方模块,开发者自己也可以开发自...详情>>
2023-11-10 14:15:30
python爬虫和数据分析有哪些第三方库?
以上内容为大家介绍了爬虫和数据分析有哪些第三方库,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http:...详情>>
2023-11-10 13:41:10
python装饰属性的方法
python中装饰属性的方法1、使用get、set方法来封装对一个属性的访问在很多面向对象编程的语言中都很常见。classStudent(object):def__init__(se...详情>>
2023-11-10 09:18:27