Python 类方法简记
文章目录
- 前言
- 必须实例化的类方法
- 使用静态装饰器的类方法
- 使用类装饰器的类方法
- 省流版本
- ref:
前言
Python 的类可以有特定的方法。下面是三种设计类方法的模板。
class A(object):a = 'a'def foo1(self, name):print 'hello', name@staticmethoddef foo2(name):print 'hello', nameprint A.a # 正常print A.foo1('mamq') # 报错: unbound method foo2() must be called with A instance as first argument (got str instance instead)@classmethoddef foo3(cls, name):print 'hello', nameprint A.aprint cls().foo2(name)
必须实例化的类方法
最常用的设计类方法的模式是 foo1。这种模式下,需要先实例化,再调用,即:
a = A()
a.foo1('mamq')
不实例化,直接调用会报错:
A.foo1('mamq')
使用静态装饰器的类方法
第二种设计类方法是使用类装饰器 @staticmethod
这种方式强调,该方法是类私有的,必须以类方法的形式调用
可以不用初始化,直接调用
a = A()
a.foo1('mamq')
A.foo1('mamq')
特点:不能用类中的其他方法,但可以用属性。
print A.a # 正常print A.foo1('mamq') # 报错: unbound method foo2() must be called with A instance as first argument (got str instance instead)
总体来说,这种方式相对轻量化,与其他类方法隔离,适用于强调方法私有化、业务逻辑相对独立的应用场景。
使用类装饰器的类方法
第三种方式是使用 cls
参数,其使用方式和第二种基本相同,但因为传进来了类本身cls
,所以能够用到类中的其他函数(不会产生上述报错)。因此这种方式更加通用,是官方推荐的一种方式。
省流版本
如果业务需要 不需要实例化,就能调用
,推荐使用 类装饰器模式
。
如果业务要求 不需要实例化,就能调用
& 类方法与其他已有的方法 相对独立
,使用 静态装饰器
。
如果业务没有上述乱七八糟的要求,使用 普通的类方法
。
ref:
https://www.zhihu.com/question/49660420