I have a class, A, which is inherited by a bunch of other classes. Some of these have a few functions which are similar and it would be nice to have those functions defined somewhere else and called by the classes that need them. But those functions call functions defined in the super class.
class A():
def imp_func(*args):
# called by the child class functions
Class B(A):
def common_func(self):
# some stuff
self.imp_func(*args)
So I have created my helper functions which take the self object
as an argument and I can call the imp_func
from inside the helper functions.
def helper_func(obj, some_args):
# some common stuff
obj.imp_func(*args)
class B(A):
def common_func(self):
# unique stuff
helper_func(self, some_args)
This solves the problem.
But should I be doing this? Is this Pythonic?
self
is just a reference to the instance, it is not private nor is it dangerous to pass it to other functions. – WillowB
inheritsimp_func
fromA
, so you can callself.imp_func(*args)
inB.common_func
without a problem. – TautonymB.common_func
callsA.imp_func
. In example 2, you haveB.common_func
callshelper_func
callsA.imp.func
. You have more code to write in the second scenario. – Brynacommon stuff
tohelper_func
while keeping onlyunique stuff
inside B. common_func() is any better or worse. – Rebel