当前位置: 首页 > 图灵资讯 > 行业资讯> Python中装饰属性的方法

Python中装饰属性的方法

发布时间:2024-08-21 22:24:38

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、property装饰器在Python中提供,可以将方法“装饰”成属性调用。

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教学

本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。

相关文章

如何让vim支持python3

如何让vim支持python3

2025-09-12
python2.7和3.6区别有哪些

python2.7和3.6区别有哪些

2025-09-12
python3有serial库吗

python3有serial库吗

2025-09-12
python中w、r表示什么意思

python中w、r表示什么意思

2025-09-12
python中如何把list变成字符串

python中如何把list变成字符串

2025-09-12
python命名空间是什么

python命名空间是什么

2025-09-12