簡體   English   中英

從python中不同類的類調用方法

[英]Calling method from a class in a different class in 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 class1(object):
    @classmethod
    def parse(cls, array):
        ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM