big*_*num 56 python oop pylint
我有一个python类并对它运行pylint.它给出的一条信息是:
Warning: Method could be a function
Run Code Online (Sandbox Code Playgroud)
这是否告诉我,将此方法移出类是更好的,因为它不使用任何实例变量?
在C#中,我会将其设为静态方法.在这里做什么最蟒蛇的事情?
Bas*_*ard 61
将它移动到函数是很常见的,如果它根本不触及类.
如果它操纵类属性,请使用classmethod
装饰器:
@classmethod
def spam(cls, ...):
# cls is the class, you can use it to get class attributes
Run Code Online (Sandbox Code Playgroud)
classmethod
和staticmethod
(这是与前者相同,只是方法不得到它的第一个参数类的引用)已经出台相当最近.这意味着一些Python程序员用于避免静态和类方法.
一些铁杆Python程序员会告诉你,这些装饰器只会使事情复杂化; 其他一些人(通常是前C#或Java程序员)会告诉你,使用一个函数不是面向对象的.我认为这只是一个偏好问题.