【问题标题】:Best Practice: Class/Static Method [duplicate]最佳实践:类/静态方法 [重复]
【发布时间】:2020-02-28 17:47:49
【问题描述】:

我想知道关于类和静态方法的最佳实践是什么(如果有的话)。

考虑下面的类

class A:
    number = 0

    @classmethod
    def add_int_m(cls, m: int) -> int:
        return cls.number + m

    @staticmethod
    def add_int_k(k: int) -> int:
        return A.number + k

两者给出相同的结果,但一种方法优于另一种方法吗?

【问题讨论】:

  • post 可能与您有关。
  • 老实说,@staticmethod 主要是一种风格/组织的东西。我很少在野外看到它,除非有人来自 Java 或 C# 之类的语言开始编写 Python 代码......

标签: python


【解决方案1】:

如果你使用类变量,你肯定要使用@classmethod,而不是@staticmethod。想象一下 B 类扩展了 A 类:

class A:
    number = 0

    @classmethod
    def add_int_m(cls, m: int) -> int:
        return cls.number + m

    @staticmethod
    def add_int_k(k: int) -> int:
        return A.number + k

class B(A):
    pass


B.number = 10

B.add_int_m(1)  # returns 11
B.add_int_k(1)  # returns 1

静态方法add_int_k仍然使用A类的变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-03
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多