【问题标题】:I am able to access and modify the class attributes through staticmethod of same class我可以通过同一类的静态方法访问和修改类属性
【发布时间】: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


【解决方案1】:

您始终可以从任何函数作为全局访问 tester 类。与classmethod 的区别在于它接收cls 作为第一个参数,这是方法绑定到的类。如果您使用静态方法对类进行子类化,这可能会有所不同。

 class Tester():
    @classmethod
    def clsmeth(cls):
        print(cls.__name__)
 
    @staticmethod
    def staticmeth():
        print(Tester.__name__)

 class Sub(Tester):
    pass

那么你的函数会表现不同。

 >>> Tester.clsmeth()
 Tester
 >>> Tester.staticmeth()
 Tester
 >>> Sub.clsmeth()
 Sub
 >>> Sub.staticmeth()
 Tester

【讨论】:

  • 谢谢@saquintes,这很好地回答了差异。
猜你喜欢
  • 2012-03-30
  • 2017-09-18
  • 2017-01-01
  • 1970-01-01
  • 2020-02-20
  • 2021-02-05
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多