简体   繁体   中英

Calling method from a class in a different class in python

Let's say I have this code:

class class1(object):
    def __init__(self):
        #don't worry about this 


    def parse(self, array):
        # do something with array

class class2(object):
    def __init__(self):
        #don't worry about this 


    def parse(self, array):
        # do something else with array

I want to be able to call class1's parse from class2 and vice-versa. I know with c++ this can be done quite easily by doing

class1::parse(array)

How would I do the equivalent in python?

It sounds like you want a static method :

class class1(object):
    @staticmethod
    def parse(array):
        ...

Note that in such cases you leave off the usually-required self parameter, because parse is not a function called on a particular instance of class1 .

On the other hand, if you want a method which is still tied to its owner class, you can write a class method , where the first argument is actually the class object:

class class1(object):
    @classmethod
    def parse(cls, array):
        ...

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