簡體   English   中英

python 中的實例方法是否需要 self 參數

[英]Do instance methods in python need a self parameter

我正在構建一個簡單的平台游戲,並在我的Sprite class 中使用我的Coords class 中的collided_left方法。 I have a attribute in the Sprite class which creates an object in the Coords class but the collided_left method doesn't have a self parameter so when I try to call it in my Sprite class, I get a name 'collided_left' is not defined error . 在不添加 self 屬性的情況下,我可以做些什么來調用該方法?

python 中的實例方法是否需要 self 參數

是的。 方法分為三種類型,即實例方法、class 方法和 static 方法。 實例方法是一種旨在對實例進行某些更改或調用另一個實例方法的方法。 因此,實例方法必須有一個 self 參數。

在不添加 self 屬性的情況下,我可以做些什么來調用該方法?

您可以將該方法更改為 static 方法。 static 方法是一種既不打算對任何實例 class 進行任何更改也不調用其他實例方法的方法。 因此,您不必傳遞 self 參數。

如果你想聲明一個 static 方法,你只需要用內置的staticmethod包裝它。 這是示例:

>>> class ThisIsClass():
    @staticmethod
    def your_method_name(a, b):
        return a + b

    
>>> instance = ThisIsClass()
>>> instance.your_method_name(1, 2)
3

暫無
暫無

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

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