Vamsi Nimmala
Vamsi Nimmala

Reputation: 507

How can I make a method variable available to inherited subclass?

Trying to invoke a method variable of superclass in the subclass.Is this possible, If possible, is it a good practice or design?

I have written an example code to execute the flow. Below is the code

class bar_for_foo_mixin():
    def __init__(self):
        self.z =0

    def bar(self, q):
        x=2
        y=8
        bar_for_foo_mixin.z= x+y+q
        print(bar_for_foo_mixin.z)

    def extented_bar(self):
        self.bar(10)


class myfoo(bar_for_foo_mixin):
    def __init__(self):
        super(myfoo, self).__init__()
        print("hello",self.z)


class oldFoo():
    def __init__(self):
        self.var = bar_for_foo_mixin()

        self.var.bar(10)

Now how can I make the Z value and make it useful in the subclass? But If Call method extended_bar() in the subclass the above code works fine, But is there any way to store the method variable of superclass and use it in the subclass?

A third class call bar method. Expected output to print. The Z vaue should store the computations done in the superclass method bar.

hello 20

Upvotes: 0

Views: 38

Answers (1)

blhsing
blhsing

Reputation: 106543

You can make the __init__ method of the subclass call the base class' __init__ method via the super() function:

class myfoo(bar_for_foo_mixin):
    def __init__(self):
        super().__init__()
        print("hello",self.z)

Moreover, since z is initialized as an instance variable, your bar function should update it as a variable bound to self instead of the class:

def bar(self, q):
    x=2
    y=8
    self.z= x+y+q
    print(self.z)

Upvotes: 2

Related Questions