欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python classmethod用处_Python classmethod类方法修饰符

发布时间:2025/3/15 python 34 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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

总结

以上是生活随笔为你收集整理的python classmethod用处_Python classmethod类方法修饰符的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。