Skip to main content
 首页 » 编程设计

名称开头没有 '_' 的 Python 类只读变量

2025年05月04日11傻小

您好,我有一个类代表或本地日历(AD 除外) 在这里,我希望所有这些类属性都是只读

class BSDate(object): 
 
def __init__(self, year, month, date): 
    self._year = year 
    self._month = month 
    self._date = date 

在 Python 解释器中,我想得到月份,所以我必须这样做:

x = BSDate(2072,5,2) 
x._month 

但我想通过简单地调用来获得月份

x.month 

我该如何解决这个问题。

请您参考如下方法:

class BSDate(object): 
    def __init__(self, year, month, date): 
        self._year = year 
        self._month = month 
        self._date = date 
 
    @property 
    def month(self): 
        return self._month 

您可以保留它,因为您现在可以使用 obj.month 访问它,如果有人尝试 obj.month = val<,它会引发 AttributeError/。但是,如果您想在运行时通知用户此行为和/或有关错误消息的更多信息,请按如下方式实现相应的 setter 。

    @property.setter 
    def month(self, value): 
        # self._month = value if you want to set 
        raise AttributeError("Very good error message") 
        # or just print to terminal that can't set and go ahead