Reputation: 901
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
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
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