【发布时间】:2021-05-28 07:22:48
【问题描述】:
我read:
静态方法也是绑定到类而不是类的对象的方法。
静态方法不能访问或修改类状态。
代码片段如下
class tester:
v1 = 10
def __init__ ( self, v2 ):
self.v2 = v2
@classmethod
def test_class_method(cls):
print (type(cls))
print(cls.__name__)
print(cls.v1)
@staticmethod
def test_static_method ( v3 ):
print (tester.v1)
tester.v1 = 20
print (tester.v1)
但我可以访问类属性并通过静态方法对其进行修改,如下所示
>>> t1 = class_methods.tester (30)
>>>
>>> class_methods.tester.test_class_method()
<class 'type'>
tester
10
>>> class_methods.tester.test_static_method(40)
10
20
>>>
【问题讨论】:
-
静态方法不像类方法或实例方法那样具有其类或实例的参数,但您仍然可以像在任何普通函数中一样访问它之外的任何内容。在上面不完整的示例中,您在静态方法中访问
tester。如果您将其作为全局访问和修改,则可以将其修改为一个。 -
那么类方法有什么不同,除了类方法将第一个参数作为类本身吗?
-
好吧,那里的措辞有点模糊。这意味着静态方法通常不知道它属于哪个类。在您的示例中,您明确告诉它修改
tester类的属性。有了classmethod,您就不必说出来了。这几乎是唯一的区别。 -
@srp:这就是区别。这是一个很大的。接收 cls 参数使您可以访问 classmethod 绑定到的类。在 staticmethod 中,您可以直接使用命名类(即 def staticmethod(...): return MyClass.property),但如果您将 MyClass 子类化,那么 staticmethod 永远不会知道实际调用它的类。
标签: python static-methods