Natsume
Natsume

Reputation: 901

Python: How to call a class in the same file

How do I call a function from a class, inside another, within the same file. My file looks like this:

class one:
    def get(self):
        return 1

class two:
    def init(self):
        get class one get()

I am trying to access the get function of class one, inside class two.

Any help is highly appreciated.

Upvotes: 2

Views: 8218

Answers (2)

NPE
NPE

Reputation: 500963

You can call One.get() directly if you turn it into a static method:

class One:
    @staticmethod
    def get():
        return 1

class Two:
    def __init__(self):
        val = One.get()

Without the @staticmethod, you need an instance of One in order to be able to call get():

class One:
    def get(self):
        return 1

class Two:
    def __init__(self):
        one = One()
        val = one.get()

Upvotes: 6

Dmitry
Dmitry

Reputation: 442

NPE's answer is correct one. Also, if you want to call class by name (string value), you can use next solution:

class_name_type = globals()['class_name']
class_object = class_name_type()

Upvotes: 3

Related Questions