Home > Net >  Inheritance of variables from a subclass
Inheritance of variables from a subclass

Time:07-26

In the code below, I have a class (MainClass) that contains two subclasses (Class1 and Class2).

class MainClass():
    def __init__(self):
        self.teste = 'abcdefg'

    class Class1():
        def __init__(self):

            self.a = 'a'
            self.b = 'b'
            self.c = 'c'

    class Class2(Class1):
        def __init__(self):

            super().__init__()

            self.d = 'a'
            self.e = 'b'
            self.f = 'c'

Class2 when receiving Class1 as inheritance, automatically inherits the variables of Class1.

Now I would like to do the same and take these other variables to my MainClass.

I managed to do some things by assigning it to a specific variable like self.values (eg: self.values.a), however, I need these variables to be inside the main class for access. (eg: self.a)

Another way that worked was, doing this workaround: `self.dict.update(self.Class2.dict)

However, I am not convinced of the method. I would like to know if there is a better way to "inherit" this subclass in my main class. Is there any way using something like super().__init__() or something like that to accept my subclass?

Thanks!

CodePudding user response:

What about if instead of inheritance you use composition, by this I mean creating an instance of Class2 in you constructor (init) method inside your main class, something like this:

# Define Class1 and Class2 at global scope
class Class1():
    def __init__(self):

        self.a = 'a'
        self.b = 'b'
        self.c = 'c'

class Class2(Class1):
    def __init__(self):

        super().__init__()

        self.d = 'a'
        self.e = 'b'
        self.f = 'c'

class MainClass():
    def __init__(self, *args, **kwargs):
        self.class_2 = Class2(*args, **kwargs)
    def some_function(self):
        some_operation = self.class_2.a * self.class_2.b
    

# Now you can access class2 variables like this (self.class_2.some_variable)

UPDATE Whay did you nested your classes inside your main class, can't you define them at global scope?

CodePudding user response:

De-indent Class1 and Class2 so that they're no longer inside MainClass. Then MainClass can inherit either of them.

class Class1:
    def __init__(self):
        self.a = 'a'
        self.b = 'b'
        self.c = 'c'

class Class2(Class1):
    def __init__(self):
        super().__init__()

        self.d = 'a'
        self.e = 'b'
        self.f = 'c'

class MainClass(Class2):
    def __init__(self):
        super().__init__()

        self.teste = 'abcdefg'
  • Related