Eugene S
Eugene S

Reputation: 6910

How to instantiate an object of a class from within the class itself?

Below is a simplified version of my code:

In TestClass.py file:

class TestClass:

    def func1(self):
        pass

    def func2(self):
        HERE I WANT TO CALL func1

And in the main.py file:

TestClass1 = TestClass()
TestClass1.func2()

Initially, I have tried to run func1 from func2 in the following way (in TestClass.py):

TestClass.func2()

But in this case I have received the following error message:

TypeError: unbound method func1() must be called with TestClass instance as first argument (got str instance instead)

So the way I understand this problem is that there is no TestClass1 instance within TestClass itself, it only exists in the main(calling) code. So in order to fix that I have passed the instance of TestClass while calling the func2 from the main.py:

TestClass.func2(TestClass1)

And I have added it (the class) to the func2 as a mandatory argument accordingly. As a result, it seem working fine. But I wanted to make sure that's it's an accepted way to do that.

Upvotes: 2

Views: 265

Answers (1)

Adam Arold
Adam Arold

Reputation: 30568

I'm not a python guru but it seems that you'll need to call func1 and func2 using the self reference this is similar to this in java.

Upvotes: 3

Related Questions