Python class run method from parent, but keep variables

Viewed 227

I have a python class, and a parent class.

class A:
    def foo(self, num):
        num1 = num + 3
        print(num1)

class B(A):
    def foo(self, num):
        super().foo(num)
        num2 = num1+3
        print(num2)

Is it possible so the child's method to keep the varables from the parents method, when it calls it in super().food(num)to use later in its own version of the method.

Or is there a better way to append to your copy of a parents method?

EDIT: My actual classes are much more complex than this. I just used this as an example. I am making an IRC bot, and wanted a base object, that the other bots could be based on. (Hence some methods will have added parts in some bots)

4 Answers

In Python, variables you assign to in a member function aren't just local to that class in the inheritence tree; they're not even available to other methods of the same class, or to that member function when you call it again later. In other words, they're just normal local variables. To assign to an object member variable, you have to explicit specify the object

class A:
    def foo(self, num):
        self.num1 = num + 3
        print(self.num1)

class B(A):
    def foo(self, num):
        super().foo(num)
        self.num2 = self.num1+3
        print(self.num2)

This method is if you want to use parent variable when returned.But I would use @Arthur Tacca, it's a bit better.

class A:
    def foo(self, num):
        num1 = num + 3
        return num1 

class B(A):
    def foo(self, num):
        num1 = super().foo(num)
        num2 = num1+3
        print(num2)
G = B().foo(4)

I think you want the init function for this. Ultimately it depends on what you are doing though. You may want an abstract class or an interface that promises certain behavior in a subclass. It's hard to say. For this problem I would do this so that bar is constructed with all of foo' s attributes

class  foo:
  def __init__(self, num1=3):
    self.num1 =num1

class bar(foo):
  def __init__(self, num2 = 3):
    foo.__init__()
    self.num2 = self.num1 + num2
Related