在Python中定义类方法的多种方法?

2024-06-01 10:16:04 发布

您现在位置:Python中文网/ 问答频道 /正文

在《潜入Python》中,马克·皮尔格林说:

When defining your class methods, you must explicitly list self as the first argument for each method

然后他在代码中给出了几个例子:

def clear(self): self.data.clear()
def copy(self):
    if self.__class__ is UserDict:
        return UserDict(self.data)
    import copy
    return copy.copy(self)

在网上浏览一些Python代码时,我遇到了@classmethod装饰器。例如:

class Logger:
    @classmethod
    def debug(msg):
        print "DEBUG: " + msg

(注意,debug函数中没有self参数)

使用self作为第一个参数和使用@classmethod装饰器定义类方法有什么区别吗?如果不是,定义类方法的一种方法是否比另一种方法更常用/更受欢迎?


Tags: 方法代码debugselfdata参数returndef
2条回答

@classmethod与定义实例方法不同。使用@classmethod定义的函数接收作为第一个参数,而不是接收特定实例的实例方法。有关详细信息,请参见Python文档here

自我不是也永远不会是含蓄的。

“自我不会变得含蓄。

让自己变得明确是件好事。它通过消除变量解析方式的模糊性使代码变得清晰。这也使得函数和方法之间的差别很小。”

http://www.python.org/dev/peps/pep-3099/

相关问题 更多 >