python:为类对象设置只读属性
我创建了一个名为“Node”的类对象。然后我创建了两个子类“甲虫”和“达科他”。您会注意到有一个名为“超类”的属性,它是基类的一部分。我想为每个子类设置这个属性,一旦设置了它,就不应该更改它。它是只读属性。我想知道如何正确设置该属性,使其成为只读属性python:为类对象设置只读属性,python,Python,我创建了一个名为“Node”的类对象。然后我创建了两个子类“甲虫”和“达科他”。您会注意到有一个名为“超类”的属性,它是基类的一部分。我想为每个子类设置这个属性,一旦设置了它,就不应该更改它。它是只读属性。我想知道如何正确设置该属性,使其成为只读属性 class Node(object): def __init__(self, name, superclass, attributes, children): self.name = name self.su
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
要在类中具有“只读”属性,可以使用@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
您可以参考另一个重命名您的变量,将
\uuu
添加到开头
self.__superclass = superclass
您无法使用类似于Dakota()的内容访问self.\uu超类
。\uu超类
如果要获取\uu超类的值
请在节点
类中添加一个函数以返回它
def getsuperclass(self):
return self.__superclass
...
Dakota().getsuperclass()
答案似乎是相关的。如果我在它前面加上一个单号怎么办?然后我能通过Dakota()得到它吗?超类是的。可以通过
Dakota()得到它。\超类
。不,只要一个单号,你就可以修改它。你也可以用两个下划线修改它。Python中没有任何内容是只读的。