【问题标题】:python: set read-only attribute for class objectspython:为类对象设置只读属性
【发布时间】:2016-02-25 15:32:16
【问题描述】:

我创建了一个名为“Node”的类对象。然后我创建了两个子类“甲虫”和“达科他”。您会注意到有一个称为“超类”的属性,它是基类的一部分。我希望为每个子类设置这个属性,一旦设置它就永远不应该改变。这是一个只读属性。我想知道如何正确设置此属性才能成为只读属性?

class Node(object):
    def __init__(self, name, superclass, attributes, children):
        self.name = name
        self.superclass = superclass
        self.attributes = attributes if attributes is not None else {}
        self.children = children if children is not None else []


    class Beetle(Node):
        def __init__(self, name="", superclass="Cars", attributes=None, children=None, enabled=True):
            super(Beetle, self).__init__(name=name, superclass=superclass, attributes=attributes, children=children)
            self.enabled = enabled


    class Dakota(Node):
        def __init__(self, name="", superclass="Trucks", attributes=None, children=None, enabled=True):
            super(Dakota, self).__init__(name=name, superclass=superclass, attributes=attributes, children=children)
            self.enabled = enabled

【问题讨论】:

标签: python


【解决方案1】:

要在类中拥有“只读”属性,您可以使用@property 装饰。

一个例子:

class Dakota(object):
def __init__(self, superclass):
    self.__superclass = superclass

    @property
    def superclass(self):
        return self.__superclass

用法:

>>> a = Dakota('lol')
>>> a.superclass
'lol'
>>> a.superclass = 'hah'
AttributeError...    

AttributeError: can't set attribute

你可以参考这个其他answer thread

【讨论】:

    【解决方案2】:

    重命名变量以将__ 添加到开头

    self.__superclass = superclass
    

    你不能用Dakota().__superclass之类的东西访问self.__superclass

    如果您想获取__superclass 的值,请在Node 类中添加一个函数以返回它。

    def getsuperclass(self):
        return self.__superclass
    ...
    
    Dakota().getsuperclass()
    

    【讨论】:

    • 如果我在它前面加上一个 _ 会怎样,然后我可以通过 Dakota()._superclass 得到它
    • 是的。可以通过Dakota()._superclass得到它。
    • 不,只有一个_,你可以修改它。
    • 你也可以用两个下划线来修改它。 Nothing 在 Python 中是只读的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    相关资源
    最近更新 更多