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

Swi*_*iss 4 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
Run Code Online (Sandbox Code Playgroud)

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

class1::parse(array)
Run Code Online (Sandbox Code Playgroud)

我将如何在 python 中做等效的事情?

Eli*_*ght 5

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

class class1(object):
    @staticmethod
    def parse(array):
        ...
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下,您会忽略通常需要的self参数,因为parse它不是在class1.

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

class class1(object):
    @classmethod
    def parse(cls, array):
        ...
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您觉得需要这样的静态方法,这强烈表明 `class1` 和 `class2` 应该是模块而不是类(或者至少 `parse` 静态方法应该是函数。) (4认同)
  • 类方法不应该将类(cls)作为第一个参数吗? (2认同)