从python中其他类中的类调用方法


问题内容

假设我有以下代码:

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

我希望能够从class2调用class1的解析,反之亦然。我知道用c ++可以很容易地做到这一点

class1::parse(array)

我将如何在python中做等效的工作?


问题答案:

听起来您想要一个静态方法

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

请注意,在这种情况下,您不必使用通常需要的self参数,因为parse不是在的特定实例上调用的函数class1

另一方面,如果您想要一个仍与其所有者类绑定的方法,则可以编写一个class
method
,其中第一个参数实际上是类对象:

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