Python中装饰属性的方法

2025-12-01 0 3,647

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

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score
 
    def get_score(self):
        return self.__score
 
    def set_score(self, score):
        self.__score = score
 
s = Student('zhangsan', 90)
s.set_score(100)
print(s.get_score())
# 输出100

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

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score
 
    @property
    def score(self):
        return self.__score
 
    @score.setter
    def score(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电脑。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 Python中装饰属性的方法 https://www.zhiup.top/2002.html

相关