网络编程
位置:首页>> 网络编程>> Python编程>> 详解python中@classmethod和@staticmethod方法

详解python中@classmethod和@staticmethod方法

作者:shaoyishi  发布时间:2022-10-24 11:47:16 

标签:python,@classmethod,@staticmethod

在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,所以可以调用类中的其他属性和方法。

来源:https://www.cnblogs.com/shaoyishi/p/16790680.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com