I'm new to python and I have a file with several classes. In a method in the class "class1" I want to use a method from another class "class2". How do I do the import and how do I call the method from class1? I have tried several different things but nothing seems to work.
You don't need to import them, because they are already in the same file.
Instead, do something like this:
class1 = Class1() #assigns class1 to your first class
Then call a method inside of Class1
like this:
Class2():
def method2(self):
class1.method1() #call your method from class2
Basically you are taking Class2()
and pointing it to the instance class2
, then you are calling a method of that class by doing class2.method2()
. It's just like calling a function from the current class, but you use instance name in front of it.
Here is an example:
class Class1():
def method1(self):
print "hello"
class Class2():
def method2(self)
class1 = Class1()
class1.method1()
Then, when you call Class2()
it will print 'hello'.
Let's say your file with all the classes is called myclass.py
with the following:
class Class2(object):
def foo(self):
return 'cabbage'
class Class1(Class2):
def bar(self):
return self.foo()
In your main script, you can import the module as usual:
import myclass
And now you can create an instance of class1
:
myinstance = myclass.Class1()
Then you can call the function directly:
myinstance.bar()
# Returns 'cabbage'
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