簡體   English   中英

python子類方法調用用非類方法覆蓋的類方法

[英]python child class method calling overridden classmethod with non-classmethod

我正在嘗試在 python3 中執行以下操作:

class Parent:
    @classmethod
    def show(cls, message):
        print(f'{message}')

    @classmethod
    def ask(cls, message):
        cls.show(f'{message}???')

class Child(Parent):
    @property
    def name(self):
        return 'John'

    def show(self, message):
        print(f'{self.name}: {message}')

instance = Child()
instance.ask('what')

但它隨后抱怨

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in ask
TypeError: Child.show() missing 1 required positional argument: 'message'

即便如此child.show按預期工作。 所以似乎child.ask正在調用Parent.show ...我也嘗試將Child.show標記為 classmethod,但是cls.name沒有顯示預期的輸出:

class Child2(Parent):
    @property
    def name(self):
        return 'John'

    @classmethod
    def show(cls, message):
        print(f'{cls.name}: {message}')

instance2 = Child2()
instance2.ask('what')

由此可見

<property object at 0xfc7b90>: what???

有沒有辦法用非類方法覆蓋父類方法,但保留其他父類方法來調用被覆蓋的方法?

我發現很難理解問題的后半部分,但我看到了一個問題,它可能會幫助您解決問題。

當您even so child.show works as expected. So it seems that child.ask is calling Parent.show even so child.show works as expected. So it seems that child.ask is calling Parent.show ,這不是正在發生的事情。

當您調用instance.ask("what")時,它調用了Child類的 @classmethod 裝飾方法(從父類繼承)。 這個ask方法將類Child作為第一個參數(不是您創建的實例)傳遞。 這意味着線

cls.show(f'{message}???')

相當於

Child.show(f'{message}???') # because cls is the Class not the instance

Child類中的 show 方法是一個實例方法,並期望第一個參數是實際實例( self ),但字符串f'{message}???' 正在傳遞給它,它希望傳遞第二個消息字符串,這就是它拋出錯誤的原因。

希望這有幫助

暫無
暫無

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

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