python:为类对象设置只读属性

标签 python

我创建了一个名为“节点”的类对象。然后我创建了两个子类“Beetle”和“Dakota”。您会注意到有一个名为“父类(super class)”的属性,它是基类的一部分。我希望为每个子类设置此属性,一旦设置,就永远不能更改。这是一个只读属性。我想知道如何正确设置此属性才能成为只读属性?

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

最佳答案

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

self.__superclass = superclass

你不能用像 Dakota().__superclass 这样的东西访问 self.__superclass

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

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

Dakota().getsuperclass()

关于python:为类对象设置只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33872535/

相关文章:

python - 如何使用复杂的自定义 id 作为选择器在 pytest 中运行单个测试?

python - Django session

javascript - django smart_selects 应用程序的问题

python - ':!' 和 '|!' 标记在 (Python) Antlr 语法中意味着什么

python - 模块未找到错误 : No module named 'requests_html'

python - Numpy 舍入性能

python - 访问循环中节点的属性

python - 如何使用应用程序 ID(服务主体)的 token 向 Azure Devops 进行身份验证?

python - CherryPy:405 Method Not allowed 指定的方法对此资源无效

python - 如何设置Scrapy规则仅解析/浏览/页面?