06.11 Python 静态方法 staticmethod 和 类方法 classmethod

Python 静态方法 staticmethod 和 类方法 classmethod

这篇文章说一下 Python 类的静态方法 staticmethod 和类方法 classmethod,以及他们有什么不同。

他们都是作为方法的装饰器使用。

实例方法 Instance Methods


通常一个类的方法是实例方法,方法的第一个参数是引用对象本身。例如:

Python 静态方法 staticmethod 和 类方法 classmethod

输出:

Python 静态方法 staticmethod 和 类方法 classmethod

上面定义了一个类 Person,构造函数 __init__ 接收一个参数 name。

我们实例化了类 Person('alex'),name 赋值为 alex。然后用实例化的对象 a 调用实例方法 hello,hello 方法的第一个参数 self就是对象 a 的引用,就可以获取到 name 的值 alex。

类方法 @classmethod


类方法不和特定的对象相关,只是和类有关。

请看如下的例子:

Python 静态方法 staticmethod 和 类方法 classmethod

输出:

Python 静态方法 staticmethod 和 类方法 classmethod

上例中,我们定义了 Person 类,每次实例化时,执行构造函数,类的属性 inst_num 加 1,调用了两次 Person(),最终打印结果 2。

可以定义一个类方法,类方法的第一个参数是类的引用。下面是改造后的例子:

Python 静态方法 staticmethod 和 类方法 classmethod

输出:

Python 静态方法 staticmethod 和 类方法 classmethod

上面定义了类方法 get_inst_num,使用装饰器 @classmethod 装饰。第一个参数我们打印出来了,就是 <class> 这个参数就是类 Person 的引用,它可以访问类属性 inst_num。/<class>

使用 @classmethod 的另一个好处是,我们用实例对象调用这个方法,第一个参数还是类引用。

Python 静态方法 staticmethod 和 类方法 classmethod

输出:

Python 静态方法 staticmethod 和 类方法 classmethod

实例对象 a 和使用类 Person 调用方法 get_inst_num 输出结果是一样的。

静态方法 @staticmethod


有时候,类中的方法和类自身或者它的实例没有任何联系。它可能访问一个全局的环境变量,或者其他类的某个属性。这个时候,可以用静态方法 @staticmethod。

Python 静态方法 staticmethod 和 类方法 classmethod

输出:

Python 静态方法 staticmethod 和 类方法 classmethod

这里使用静态方法 debugon,我们在它定义上方使用 @staticmethod 装饰器装饰。

它访问全局变量 DEBUG_PERSON,返回布尔类型,提示是否打开调试。如果打开调试,就在调用 hello() 方法的时候打印调试信息。

静态方法可以由 self 调用。


分享到:


相關文章: