本文共 1142 字,大约阅读时间需要 3 分钟。
classmethod 修饰符将函数转换为类方法。类方法将类作为隐式第一个参数接收,就像实例方法接收实例一样。
类方法声明格式:class C: @classmethod def f(cls, arg1, arg2, ...): ...
它可以在类(例如C.f())或实例(例如C().f())上调用。实例被忽略,但它的类除外。如果为派生类调用类方法,则派生类对象作为隐含的第一个参数传递。
类方法第一个参数cls表示自身类,可以来调用自身类的属性,类的方法,实例化对象等。 实例演示: classmethod.py内容如下#!/usr/bin/python# -*- coding: UTF-8 -*-class C(object): y = 10 def func1(self): #需要实例化才能调用 print('func1') @classmethod def func2(cls): #不需要实例化就能调用 print("func2 start") print("C.y =", cls.y) #类属性不需要实例化就能调用 new_cls = cls() new_cls.func1() try: cls.func3() except TypeError as e: print(e) print("func2 end") def func3(): #python2需要实例化之后调用,python3不需要实例化就能调用 print("func3")C.func2()X.func2()
python2和python3的运行结果如下
[sudley@CSDN /home/Sudley/Python]#python2 classmethod.pyfunc2 start('C.y =', 10)func1unbound method func3() must be called with C instance as first argument (got nothing instead)func2 end[sudley@CSDN /home/Sudley/Python]#python3 classmethod.pyfunc2 startC.y = 10func1func3func2 end[sudley@CSDN /home/Sudley/Python]#
转载地址:http://zyiti.baihongyu.com/