如果 __init__ 中未定义该属性,则显示 class 的属性?

Displaying an attribute of a class if that attribute is not defined in __init__?

class MyClass:

def __init__(self,n):
    self.x = n

def set_y(self):
    self.y = self.x * 2

obj = MyClass(2)
obj.set_y
obj.__dict__

输出:

{'x': 2}

我的问题是,虽然调用了实例方法set_y,但是obj.__dict__并没有显示y。是不是因为y里面没有定义__init__

未调用方法 set_y,因为您忘记了括号。

应该是:

obj.set_y()