当前位置:首页 > 系统运维

为什么 Classmethod 比 Staticmethod 更受宠?

 我们知道,更受classmethod 和 staticmethod 都可以作为函数的更受装饰器,都可用于不涉及类的更受成员变量的方法,但是更受你查一下 Python 标准库就会知道 classmethod 使用的次数(1052)要远远多于 staticmethod(539),这是更受为什么呢?

这就要从 staticmethod 和 classmethod 的区别说起。

1、更受从调用形式上看,更受二者用法差不多

先说下什么是更受类,什么是更受实例,比如说 a = A(),更受那么 A 就是更受类,a 就是更受实例。

从定义形式上看,更受clasmethod 的更受第一个参数是 cls,代表类本身,更受普通方法的第一个参数是 self,代表实例本身,staticmethod 的参数和普通函数没有区别。亿华云计算

从调用形式上看,staticmethod 和 classmethod 都支持类直接调用和实例调用。

class MyClass:     def method(self):         """         Instance methods need a class instance and         can access the instance through `self`.         """         return instance method called, self     @classmethod     def classmethod(cls):         """         Class methods dont need a class instance.         They cant access the instance (self) but         they have access to the class itself via `cls`.         """         return class method called, cls     @staticmethod     def staticmethod():         """         Static methods dont have access to `cls` or `self`.         They work like regular functions but belong to         the classs namespace.         """         return static method called # All methods types can be # called on a class instance: >>> obj = MyClass() >>> obj.method() (instance method called, <MyClass instance at 0x1019381b8>) >>> obj.classmethod() (class method called, <class MyClass at 0x101a2f4c8>) >>> obj.staticmethod() static method called # Calling instance methods fails # if we only have the class object: >>> MyClass.classmethod() (class method called, <class MyClass at 0x101a2f4c8>) >>> MyClass.staticmethod() static method called 

2、先说说 staticmethod。

如果一个类的函数上面加上了 staticmethod,通常就表示这个函数的计算不涉及类的变量,不需要类的实例化就可以使用,也就是说该函数和这个类的关系不是很近,换句话说,使用 staticmethod 装饰的函数,也可以定义在类的外面。我有时候会纠结到底放在类里面使用 staticmethod,还是放在 utils.py 中单独写一个函数?比如下面的 Calendar 类:

class Calendar:     def __init__(self):         self.events = []     def add_event(self, event):         self.events.append(event)     @staticmethod     def is_weekend(dt:datetime):         return dt.weekday() > 4 if __name__ == __main__:     print(Calendar.is_weekend(datetime(2021,12,27)))     #output: False 

里面的函数 is_weekend 用来判断某一天是否是周末,就可以定义在 Calendar 的外面作为公共方法,这样在使用该函数时就不需要再加上 Calendar 这个类名。

但是有些情况最好定义在类的里面,服务器租用那就是这个函数离开了类的上下文,就不知道该怎么调用了,比如说下面这个类,用来判断矩阵是否可以相乘,更易读的调用形式是 Matrix.can_multiply:

from dataclasses import dataclass @dataclass class Matrix:     shape: tuple[int, int] # python3.9 之后支持这种类型声明的写法     @staticmethod     def can_multiply(a, b):         n, m = a.shape         k, l = b.shape         return m == k 

3、再说说 classmethod。

首先我们从 clasmethod 的形式上来理解,它的第一个参数是 cls,代表类本身,也就是说,我们可以在 classmethod 函数里面调用类的构造函数 cls(),从而生成一个新的实例。从这一点,可以推断出它的使用场景:

当我们需要再次调用构造函数时,也就是创建新的实例对象时

需要不修改现有实例的情况下返回一个新的实例

比如下面的代码:

class Stream:     def extend(self, other):         # modify self using other         ...     @classmethod     def from_file(cls, file):         ...     @classmethod     def concatenate(cls, *streams):         s = cls()         for stream in streams:             s.extend(stream)         return s steam = Steam() 

当我们调用 steam.extend 函数时候会修改 steam 本身,源码库而调用 concatenate 时会返回一个新的实例对象,而不会修改 steam 本身。

4、本质区别

我们可以尝试自己实现一下 classmethod 和 staticmethod 这两个装饰器,来看看他们的本质区别:

class StaticMethod:     def __init__(self, func):         self.func = func     def __get__(self, instance, owner):         return self.func     def __call__(self, *args, **kwargs):  # New in Python 3.10         return self.func(*args, **kwargs) class ClassMethod:     def __init__(self, func):         self.func = func     def __get__(self, instance, owner):         return self.func.__get__(owner, type(owner)) class A:     def normal(self, *args, **kwargs):         print(f"normal({ self=}, { args=}, { kwargs=})")     @staticmethod     def f1(*args, **kwargs):         print(f"f1({ args=}, { kwargs=})")     @StaticMethod     def f2(*args, **kwargs):         print(f"f2({ args=}, { kwargs=})")     @classmethod     def g1(cls, *args, **kwargs):         print(f"g1({ cls=}, { args=}, { kwargs=})")     @ClassMethod     def g2(cls, *args, **kwargs):         print(f"g2({ cls=}, { args=}, { kwargs=})") def staticmethod_example():     A.f1()     A.f2()     A().f1()     A().f2()     print(f{ A.f1=})     print(f{ A.f2=})     print(A().f1)     print(A().f2)     print(f{ type(A.f1)=})     print(f{ type(A.f2)=}) def main():     A.f1()     A.f2()     A().f1()     A().f2()     A.g1()     A.g2()     A().g1()     A().g2()     print(f{ A.f1=})     print(f{ A.f2=})     print(f{ A().f1=})     print(f{ A().f2=})     print(f{ type(A.f1)=})     print(f{ type(A.f2)=})     print(f{ A.g1=})     print(f{ A.g2=})     print(f{ A().g1=})     print(f{ A().g2=})     print(f{ type(A.g1)=})     print(f{ type(A.g2)=}) if __name__ == "__main__":  main() 

上面的类 StaticMethod 的作用相当于装饰器 staticmethod,类ClassMethod 相当于装饰器 classmethod。代码的执行结果如下:

可以看出,StaticMethod 和 ClassMethod 的作用和标准库的效果是一样的,也可以看出 classmethod 和 staticmethod 的区别就在于 classmethod 带有类的信息,可以调用类的构造函数,在编程中具有更好的扩展性。

最后的话

回答本文最初的问题,为什么 classmethod 更受标准库的宠爱?是因为 classmethod 可以取代 staticmethod 的作用,而反过来却不行。也就是说凡是使用 staticmethod 的地方,把 staticmethod 换成 classmethod,然后把函数增加第一个参数 cls,后面调用的代码可以不变,反过来却不行,也就是说 classmethod 的兼容性更好。

另一方面,classmethod 可以在内部再次调用类的构造函数,可以不修改现有实例生成新的实例,具有更强的灵活性和可扩展性,因此更受宠爱,当然这只是我的拙见,如果你有不同的想法,可以留言讨论哈。

本文转载自微信公众号「Python七号」,可以通过以下二维码关注。转载本文请联系Python七号公众号。

分享到:

滇ICP备2023006006号-16