即使不使用 Python self 参数也需要它吗?

Spo*_*ech 1 python warnings self


我可以理解Python要求self作为第一个参数,而不是什么。然而,我对 PyCharm 告诉我方法“hello”需要 self 作为第一个参数(当它甚至没有被使用时)感到困惑。

举个例子:

class Example:
    def hello():
       return "hello world"
Run Code Online (Sandbox Code Playgroud)

这会给我一个错误,说“方法必须有第一个参数,通常称为 self”

即使函数/方法没有使用它,我是否仍然应该将 self 作为参数包含在内,还是应该忽略此错误/警告?这是因为该方法位于类内部吗?

Ofe*_*dan 6

self方法有多种类型,默认的是实例方法,即使不使用也必须有一个,但如果self不使用,最好将其定义为静态方法或类方法

class Example:
    @staticmethod
    def statichello():
        return "hello world"

    @classmethod
    def classhello(cls):
        return "hello world from " + str(cls)

    def hello(self):
        return "hello world from " + str(self)
Run Code Online (Sandbox Code Playgroud)

类和静态方法可以在有或没有实例的情况下调用:

>>> Example.statichello()
'hello world'
>>> Example().statichello()
'hello world'
>>> Example.classhello()
"hello world from <class '__main__.Example'>"
>>> Example().classhello()
"hello world from <class '__main__.Example'>"
Run Code Online (Sandbox Code Playgroud)

但必须从实例调用实例方法:

>>> Example().hello()
'hello world from <__main__.Example object at 0x000002151AF10508>'
Run Code Online (Sandbox Code Playgroud)