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)
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)
You could define num1 as an instance variable, then you will be able to use it in your B class.
class A(object):
def foo(self, num):
self.num1 = num + 3
print(self.num1)
class B(A):
def foo(self, num):
super(B, self).foo(num)
num2 = self.num1 + 3
print(num2)
https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With