Home > Software design >  How to access attributes of the __init_ function
How to access attributes of the __init_ function

Time:10-19

is there a way to access attributes of init without assigning them to self.attribute = attribute For example:

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

def f(self):
    print(o)

j = test()
j.f()

I want that the __init__argument get printed without assigning self.o = o in the constructor and using print(self.o) in f

I just want to spare code, for example by using something like that in the print statement of f: print(test.init.o) or something like that

CodePudding user response:

Well, while this is possible, using some of Python's inspection capabilities:

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

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

what is the point of it?

Function parameters are local to the function for good reason: to be used there and only there.

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