Suppose I have this class:
class MyClass(object):
def uiFunc(self, MainWindow):
self.attr1 = "foo"
self.attr2 = "bar"
def test():
from subclassfile import MySubClass
MySubClass.firstFunc(self, 2, 2)
test()
And this subclass in other file:
from classfile import MyClass
class MySubclass(MyClass):
def firstFunc(self, a, b):
c = a + b
d = self.secondFunc(self, c)
return d
def secondFunc(self, c):
d = c / 2
return d
This is a silly example, but represents exactly what I’m trying to do.
I want to call the second function from the subclass inside the first function.
But when I do that it returns an error that says that MyClass doesn’t have such function.
So I suppose that I shouldn’t be using the self in front of the function name when I call it. But when I don’t it raises an error too.
So my question is:
How do I access this second function inside the first function of a subclass?
EDIT:
Thank you all for the help. I’ll explain better what I’m trying to do while I guess that my implementation is really bad in the code.
MyClass is the main Class of the code, where all the widgets and main functions are.
There is also a button on this Class that is binded with the “test” function. So when the button is pressed the whole thing should work.
The MySubClass file is an auxiliary module that exports data to some file.
The firstFunc is the main function in this module that handles with all the data while secondFunc just builds the template of the file. So I call this secondFunc inside the firstFunc so that the template is loaded and then the data is written in the file.
I made this MySubClass inherited from the MyClass so that it could have access to the database and other variables directly from the MyClass.
So I suppose that I could do this otherway. But I’m not really experienced with this kind of implementation. Also, sorry for my bad english.
You don’t call this method from an instance of
MyClass, You call it from an instance ofMySubclass. The problem is that you’re probably getting aTypeErrorsince the argument (self) that you’re passing tofirstFuncis the wrong type (MyClassinstead ofMySubClass). The solution is to restructure your code so this doesn’t happen. At least, I assume that’s the problem (when I tried you code, I got all sorts of import errors). Here’s the code that I tried (which I assume illustrates the problem you’re describing):Notice that it doesn’t really make sense to have
testas a method ofMyClassbecause you can’t use it from there anyway. You might as well just movetestontoMySubClass.Also, as others have noted,
self.secondfunc(self,c)is also very strange. This is basically equivalent toMySubClass.secondfunc(self,self,c)which has the wrong number of arguments, as you’re passingselftwice.This works:
But I highly recommend restructuring your code.