【问题标题】:How to handle the pylint message: Warning: Method could be a function如何处理 pylint 消息:警告:方法可能是函数
【发布时间】:2010-04-20 09:46:19
【问题描述】:

我有一个 python 类并针对它运行 pylint。它给出的一条信息是:

Warning: Method could be a function

这是否告诉我最好将此方法移出类,因为它不使用任何实例变量?

在 C# 中,我会将其设为静态方法。这里最蟒蛇的事情是什么?

【问题讨论】:

    标签: python oop pylint


    【解决方案1】:

    将它移到一个函数是很常见的,如果它根本不涉及类的话。

    如果它操作类属性,请使用classmethod 装饰器:

    @classmethod
    def spam(cls, ...):
       # cls is the class, you can use it to get class attributes
    

    classmethodstaticmethod(与前者相同,只是该方法没有从其第一个参数中获取对类的引用)最近才被引入。 这意味着一些 Python 程序员习惯于避免使用静态和类方法。

    一些铁杆 Python 程序员会告诉你,这些装饰器只会使事情复杂化;其他一些人(通常是以前的 C# 或 Java 程序员)会告诉您使用函数还不够面向对象。 我认为这只是一个偏好问题。

    【讨论】:

    • 我认为@staticmethod 在这里比@classmethod 更合适,因为它显然不操纵任何类属性或状态。
    • Java 程序员也使用静态方法
    • 同意.. 正如@mcepl 所建议的,它应该是@staticmethod
    • 堆放在其他 cmets 上,如果您仍然希望该函数成为该类的一部分,请使用 staticmethod。欲了解更多信息,see here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多