假设我有这个代码:
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 中做等效的事情?
听起来你想要一个静态方法:
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)