程序员

python classmethod使用场景

2019-10-07  本文已影响0人  祖传编程

平时自己比较常用的是staticmethod,那么classmethod使用场景是什么呢?

先看语法:

class Test(object):

    @classmethod

    def class_method(cls):

        print("是类方法")

类方法,第一个参数必须要默认传类,一般习惯用cls。

在网上看了很多介绍文档,感觉说法还是有问题,比如:类方法中可以调用静态方法,继承里的类方法和静态方法差异,这些感觉只是语法差异,并不是类方法的使用场景。

下面拿python中datetime类来说明类方法真正的作用:

class Time:

    def __init__(self, day_frac, *, to_utc=None):

        xxx#一堆初始化

    @classmethod

    def now(cls, to_utc=None):

        current_moment = get_moment_complete()

        local = cls(current_moment[1], to_utc=current_moment[2])

        if to_utc is None:

            return local

        else:

            return local.relocate(new_to_utc=to_utc)

    @classmethod

    def localnow(cls):

        current_moment = get_moment_complete()

        return cls(current_moment[1])

    @classmethod

    def utcnow(cls):

        current_moment = get_moment_complete()

        now = current_moment[1] + current_moment[2]

        if now < 0:

            now += 1

        elif now >= 1:

            now -= 1

        return cls(now)

类的初始化函数有固定格式,如果使用者需要其他格式的参数来做初始化,没有提供的这些类方法,就需要自己做处理。

比如Time类中的now方法,如果没有提供类方法,就需要用户自己处理然后传参构建。提供到类方法里,就相当于有了多个构造函数,在类方法里重新创建实例对象

所以说classmethod的设计也是比较高级的,可能大家也看出来了,其实这就是工厂模式,每个类方法可以看做是工厂方法所以它的真正使用场景应该是:需要重建类对象时。当然,如果利用cls传参这个特性来实行一些其他功能也未尝不可。

上一篇 下一篇

猜你喜欢

热点阅读