user1234440
user1234440

Reputation: 23607

Python Passing Class Object in to anther Class

If I have two files class1_file.py and class2_file.py and each of them has got classes class1 and class2.

class1_file.py

class class1:
    def dummy(self, class2):
        class2.dummy()

class2_file.py:

class class2
    def dummy(self):
        print 'hey'

Will I need to include: from class2_file import class2 in to class1_file.py for the method in class1 dummy to work? I am a bit confused as I came from strong type language which requires to import classes and passing them into methods for use. But for python it seems the argument can be of any type and it will resolve it at compilation. If it is not required, how does the method in class1 know what is coming in to the function dummy for class1?

Upvotes: 1

Views: 103

Answers (3)

thefourtheye
thefourtheye

Reputation: 239683

If your intention is to pass an object of class2 to class1's dummy, then to create an object of class2 you need to import class2.

from class2_file import class2
class class1:
    def dummy(self, obj):      # To avoid confusion changed the variable name
        obj.dummy()

class1().dummy(class2())       # import is needed for `class2()` part only

Apart from that, class2 is just a variable name, that could be anything. That is why I changed it to obj in this answer.

When you do class2() Python will look for the definition of class2 in all the valid scopes and it will not be found. But when you do

from class2_file import class2

you are introducing class2 as a local name in this module. So, Python would be able to recognize it.

    def dummy(self, class2):
        class2.dummy()

When you create a function like this, Python will try to execute class2.dummy() and it will class2 as the parameter, not as the class, because class2 is the nearest name in scope. And as long as the value passed for class2 has dummy method, that line will be evaluated properly.

Upvotes: 1

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

Don't name the variable class2. And yes, you will need to import class2 from class2_file.

from class2_file import class2

class class1:
    def dummy(self, class2_obj):
        class2_obj.dummy()

Upvotes: 1

zhangxaochen
zhangxaochen

Reputation: 34047

no you don't have to, because in signature def dummy(self, class2): class2 is just a local variable in method dummy. It can also be def dummy(self, foo): as long as foo is an object with method dummy. See Duck typing in Python.

Upvotes: 1

Related Questions