简体   繁体   中英

call @classmethod from another @classmethod of another class

I have two python files as

one.py

class FirstClass:
    @classmethod
    def myClass(cls,first, second):
        return first+second

two.py

from one import FirstClass

class SecondClass:
    @classmethod
    def herClass(cls, val1, val2):
        FirstClass.myClass(val1,val2)

ob = SecondClass()
print(ob.herClass(2,3))

How can I access the classmethod of one class from the classmethod of another class. If not possible, what might be the possible solution. FirstClass needs to remain same, I have flexibility changing the method type on SecondClass.

It's possible, but you're missing the return of this function

def herClass(cls, val1, val2):
        return FirstClass.myClass(val1,val2)

There is nothing wrong with your implementation just add return statement in SecondClass.herClass

Corrected code will look like this

class SecondClass:
    @classmethod
    def herClass(cls, val1, val2):
        return FirstClass.myClass(val1,val2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM