1

Python的OOP概念中有三种方法——实例方法、类方法和静态方法。

class MyClass:
    def instancemethod(self):
        return 'instance method called'

    @classmethod
    def classmethod(cls):
        return 'class method called'

    @staticmethod
    def staticmethod():
        return 'static method called'

很明显知道所有三种方法。现在我在一个类中创建一个新方法:

class Test():
    def ppr():
        print('what method is ppr?')

它不是实例方法。

inst = Test()
inst.ppr()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ppr() takes 0 positional arguments but 1 was given

所以它是一个类方法?

Test.ppr()
what method is ppr?

没有@classmethod关键字来装饰ppr函数。

4

2 回答 2

2

让我们测试一下:

class MyClass:
    def instancemethod(self):
        return 'instance method called'

    @classmethod
    def classmethod(cls):
        return 'class method called'

    @staticmethod
    def staticmethod():
        return 'static method called'

class Test():
    def ppr():
        print('what method is ppr?')

print(type(MyClass.instancemethod)) # -> function
print(type(MyClass.classmethod))    # -> method
print(type(MyClass.staticmethod))   # -> function 

print(type(Test.ppr))               # -> function 

AsTest.ppr作为一个函数返回,它可以在不创建实例的情况下运行 - 它是一个@staticmethod.

如果它是一个相反的 - 它会作为 type method@classmethod回来。

qed


我的 IDE 向我显示警告:“方法 ppr 没有参数。” 这暗示您可能应该添加 aself或 acls以及与之对应@classmethod的内容。

要回答您的问题 - 似乎不需要(此时) - 但谨慎的做法是声明它们@staticmethod以明确您的意图。

于 2021-09-28T13:37:50.163 回答
0

对于普通的静态方法,它可以由类或实例调用。

#called by class 
MyClass.staticmethod()
'static method called'
#called by instance
MyClass().staticmethod()
'static method called'

类中的方法Test是非标准的static method

Test.ppr()
what method is ppr?
Test().ppr()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ppr() takes 0 positional arguments but 1 was given
于 2021-09-29T00:53:45.680 回答