面向对象中怎么实现只读属性?

本文阅读 1 分钟
首页 › Python笔记 › 正文

将对象私有化,通过共有方法提供一个读取数据的接口

class person:
    def __init__(self, x):
        self.__age = 10
    def age(self):
        return self.__age
t = person(22)
# t.__age =100
print(t.age())

最好的方法

class MyCls(object):
    __weight = 50
    
    @property
    def weight(self):
        return self.__weight
   
Python的魔法方法
« 上一篇 01-31
谈谈你对面向对象的理解?
下一篇 » 01-31

发表评论