如何访问 __init_ 函数的属性

How to access attributes of the __init_ function

有没有办法访问 init 的属性而不将它们分配给 self.attribute = 属性 例如:

class test:
def __init__(self, o = "hi"):
   pass

def f(self):
    print(o)

j = test()
j.f()

我希望打印 __init__argument 而无需在构造函数中分配 self.o = o 并在 f

中使用 print(self.o)

我只是想节省代码,例如在 f 的打印语句中使用类似的东西: print(test.init.o) 或类似的东西

虽然这是可能的,但使用 Python 的一些检查功能:

class test:
    def __init__(self, o="hi"):
        pass
    def f(self):
        print(self.__init__.__func__.__defaults__[0])

j = test()
j.f()
# hi

它有什么意义?

函数参数是函数的局部参数是有充分理由的:在那里使用,在那里。

class test:
    def __init__(self, o="hi"):
        self.o = o
    def f(self):
        print(self.o)