从python中不同类的类调用方法

时间:2010-07-22 18:16:04

标签: 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中执行等效操作?

1 个答案:

答案 0 :(得分:4)

听起来你想要一个static method

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

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

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

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