Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import class in same file in Python [closed]

Tags:

python

import

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.

like image 848
Sofie Molin Andersson Avatar asked Jul 03 '13 10:07

Sofie Molin Andersson


2 Answers

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'.

like image 91
Serial Avatar answered Oct 21 '22 22:10

Serial


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'
like image 3
TerryA Avatar answered Oct 21 '22 22:10

TerryA