[Python] 详解python中@classmethod和@staticmethod方法

2233 0
王子 2022-11-9 15:37:39 | 显示全部楼层 |阅读模式
在python类当中,经常会遇到@classmethod和@staticmethod这两个装饰器,那么到底它们的区别和作用是啥子呢?具体来看下。
    @classmethod :默认有一个cls参数,用类或对象都可以调用。@staticmethod:静态方法,无默认参数,用类和对象都可以调用。
1.@staticmethod:

我们看下代码:
class A:
    def f1(x):
        print(x)

A.f1(2)  # 2  类.函数创建一个类,通过类调用函数。
class A:
    @staticmethod
    def f1(x):
        print(x)

A.f1(2)  # 2  类.静态方法
A().f1(2)  # 2 对象.静态方法  这种情况下是可以执行的,如果上述f1没有被staticmethod装饰那么就会报错!!!创建一个类,通过类调用函数。同时,因为该方法被staticmethod装饰器装饰了,那么通过对象.方法也是可以调用的。
所以在类中,通过@staticmethod装饰的函数,可以直接被类调用,也可以被实例化后的对象调用!!!
同时,发现@staticmethod装饰的函数根本不需要传递self这个参数。因为被@staticmethod装饰的函数是直接绑定在类上而不是对象上。
2.@classmethod:

class A:
    @classmethod
    def f1(cls,x):
        print(x)

A.f1(2)  # 2  类.方法
A().f1(2) # 2  对象.方法创建一个类,通过类调用函数。同时,因为该方法被classmethod装饰器装饰了,那么通过对象.方法也是可以调用的。但注意,在被装饰方法中,必须传递cls参数!!!
class B:
    name = 'bruce'
    age = 16
    @classmethod
    def f1(cls,x):
        print(x)
        print(cls.age)
        print(cls.name)
B().f1(1)
# 1
# 16
# bruce上述中,说明被classmethod装饰后的方法,通过cls参数,在该方法中,可以调用该类的属性。
class C:

    @classmethod
    def f1(cls,x):
        print(x)
        cls().f2()

    def f2(self):
        print('hello world')

C.f1(1) 或者 C().f1(1)# 1<br># hello world上述中,说明被classmethod装饰后的方法,通过cls参数,在该方法中,可以调用该类的其他方法。
所以在类中,通过@classmethod装饰的函数,首先在方法中必须传递第一个参数cls, 该函数可以被类直接调用,也可以被对象调用!!!
同时,因为传递了一个cls,所以可以调用类中的其他属性和方法。
到此这篇关于详解python中@classmethod和@staticmethod方法的文章就介绍到这了,更多相关python中@classmethod和@staticmethod内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行