Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to call a class in the same file

Tags:

python

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.

like image 915
Natsume Avatar asked Jun 23 '26 00:06

Natsume


1 Answers

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()
like image 54
NPE Avatar answered Jun 25 '26 12:06

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!