【发布时间】:2022-11-12 00:44:40
【问题描述】:
我写了一个类,它有 3 个隐藏属性:
class Car():
def __init__(self, name, model, brand):
self.__name = name
self.__model = model
self.__brand = brand
是否可以为此类创建一个方法来设置新属性(发布者)? 我写了这个,但我没有得到结果:
def set_publisher(self, publisher):
self.__publisher = publisher
b1 = Car(name="X", model="Y", brand="Z")
publisher="D"
b1.set_publisher(publisher)
错误:
AttributeError: 'Car' object has no attribute 'set_publisher'
【问题讨论】:
-
它没有属性
set_publisher。但是一旦你调用了set_publisher(),它就应该有一个__publisher属性。 -
是否可以不在 __init__() 中定义发布者?
-
我转载了你的问题。尝试使用以单个下划线(不是 2)为前缀的变量。当用
_publisher替换__publisher时,它对我有用。我相信双下划线前缀的变量是保留的。除非你真的想要__变量。 -
奇怪的。你能仔细检查缩进吗?
set_publisher()函数是否属于该类?一个简单的缩进错误可能会导致该问题。我试过了。 -
@0x0fba
__publisher不是保留的(__publisher__是保留的,后面也有下划线)。但是,当一个下划线将其标记为“不是公共接口的一部分”就足够了时,人们经常使用受名称修饰的名称。
标签: python python-3.x