Home > front end >  reference instance attribute in child class
reference instance attribute in child class

Time:04-26

I am trying to call an instance variable from a "parent" class (subclass) to it's "child" class (subsubclass)

class mainclass():
    def __init__(self):
        self.mainclassvar1 = "mainclass"

class subclass(mainclass):
    def __init__(self):
        self.subclassvar1 = "subclass"

    def changeval(self):
        self.subclassvar1 = "subclassedited"

class subsubclass(subclass):
    def __init__(self):
        self.subsubclassvar1 =  subclass.subclassvar1 #<- naturally this fails


def handler():
    main=mainclass()
    sub = subclass()
    sub.changeval()
    subsub = subsubclass()
    print(subsub.subsubclassvar1)# <- how do I achieve this? I would expect "subclassedited" but it doesn't
if __name__ == "__main__":
    handler()

The above does not work obviously but I am trying to show what I am trying to achieve in my head.

if I change the class subsubclass(subclass) as follows it semi-works:

class subsubclass(subclass):
    def __init__(self):
        subclass.__init__(self)
        self.subsubclassvar1 =  self.subclassvar1

however the returned value is the original default value of subclass instead of the expected subclassedited.

I am not sure if I should even be trying to do this but I've got some code where the logic has now come to this point and I want to try see if I can get details from the middle class in to the final child class in their final modified states instead of the defaults and without refactoring a lot of code.

CodePudding user response:

Each __init__ method should be invoking the parent's __init__ method, so that the instance is properly initialized for all the classes in the hierarchy.

class mainclass:
    def __init__(self):
        super().__init__()
        self.mainclassvar1 = "mainclass"

class subclass(mainclass):
    def __init__(self):
        super().__init__()
        self.subclassvar1 = "subclass"

    def changeval(self):
        self.subclassvar1 = "subclassedited"

class subsubclass(subclass):
    def __init__(self):
        super().__init__()
        # Not sure why you would really need this, but...
        self.subsubclassvar1 =  self.subclassvar1

There's no reason, though that subsub.subclassvar1 should be related to sub.subclassvar1, though. Calling sub.changeval() has nothing to do with subsub.

  • Related