• 技术文章 >Python技术 >Python基础教程

    Python中装饰属性的方法

    小妮浅浅小妮浅浅2021-05-26 09:42:52原创2046

    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电脑。

    专题推荐:python装饰属性
    品易云
    上一篇:Python魔术方法的三个特点 下一篇:Python死锁的产生原因

    相关文章推荐

    • Python中__slots__的禁用实例• Python函数调用跟踪装饰器• Python双向队列是什么• Python如何标识线程?• Python实例属性的优先级分析• Python类成员的访问限制• Python魔术方法的三个特点

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网