zoukankan      html  css  js  c++  java
  • Python中的@classmethod是如何使用的?

    在写Python程序的时候,特别是实现类方法的时候,通常会用到@staticmethod和@classmethod两种装饰器(function decorator),那这两个装饰器有什么作用呢?在这篇博文中将主要看看@classmethod是如何工作的。

    @classmethod是Python内置(built-in)的函数装饰器,其主要作用将类方法中的函数方法(实例方法)转换为类方法。

    具体的一个使用方式如下所示:

    1 class A():
    2     @classmethod
    3     def B(cls, arg1, arg2):
    4         return cls(arg1, arg2)

    看上面代码有点抽象,不明白这么做的意义和作用是啥。没事,通过例子来看看就明白@classmethod是如何工作的。

    from datetime import date
    class Student(object):
    
        def __init__(self, name, age):
            self.name = name
            self.age= age
        
        @classmethod
        def from_year(cls, name, birth_year):
            return cls(name, date.today().year - birth_year)
    
    
    student1 = Student("小王", 15)
    student2 = Studeng("小李", 2006)
    
    print(student1.age)
    print(student2.age)

    从上面可以看出,from_year这个函数是构造student这个对象的另外一个类方法。但是使用了不同的传参手段和处理方式。

  • 相关阅读:
    Java8新特性一览表
    FastDFS 单机部署指南
    EntityManager的Clear方法的使用
    元类
    python中的函数的分类
    python中的多任务
    正则表达式
    GIL和copy
    文件管理
    logging日志模块配置
  • 原文地址:https://www.cnblogs.com/jielongAI/p/11718535.html
Copyright © 2011-2022 走看看