编程语言
首页 > 编程语言> > Python classmethod类方法修饰符

Python classmethod类方法修饰符

作者:互联网

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的运行结果如下

[root@CSDN /home/Sudley/Python]#python2 classmethod.py
func2 start
('C.y =', 10)
func1
unbound method func3() must be called with C instance as first argument (got nothing instead)
func2 end
[root@CSDN /home/Sudley/Python]#python3 classmethod.py
func2 start
C.y = 10
func1
func3
func2 end
[root@CSDN /home/Sudley/Python]#

标签:func2,调用,Python,修饰符,classmethod,实例,print,cls
来源: https://blog.csdn.net/Sudley/article/details/110679754