簡體   English   中英

在另一個class方法中調用class方法

[英]Call class method in another class method

Python 3、如何在另一個class方法中調用繼承的方法?

class A:
    name = 'foo'

    def get_name(self):
        return self.name


class B(A):

    @classmethod
    def do_other(cls):
        cls.get_name()

在 cls.get_name() 中,它抱怨“參數“self”未填充”。 我怎樣才能克服這個問題而不必將 do_other 更改為常規方法?

您可以通過創建臨時實例來完成此操作。 這是一種方式。

 class A:
    name = 'foo'
    
    def __init__(self):
        self.name = A.name
    
    def get_name(self):
        return self.name


class B(A):

    @classmethod
    def do_other(cls):
        return B.get_name(cls)


print(B.do_other())

這是第二種方式

class B(A):

@classmethod
def do_other(cls):
    return A().get_name()

在這里你也可以用 B() 替換 A() 因為 class B 繼承自 class A

你實際上只需要返回cls.get_name(cls)

class A:
    name = 'foo'
    def get_name(self):
        return self.name


class B(A):
    @classmethod
    def do_other(cls):
        return cls.get_name(cls)


print(B.do_other())

暫無
暫無

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

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