1. 首页
  2. 编程面试题
  3. Python
  4. 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()) #  10

最好的方法
class MyCls(object):
    __weight = 50
    @property
    def weight(self):
        return self.__weight
m = MyCls()
print(m.weight) # 50

发布者:admin,如若转载,请注明出处:https://ai1024.vip/38118.html

QR code
//