zoukankan      html  css  js  c++  java
  • @classmehod 用法解析

    classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

    class A(object):
    bar = 1
    def func1(self):
    print('foo')
    @classmethod
    def func2(cls):
    print('func2')
    print(cls.bar)
    cls().func1()


    A.func2()

    class Date_test(object):
    day = 0
    month = 0
    year = 0
    def __init__(self,year=0,month =0,day = 0):
    self.day = day
    self.month = month
    self.year = year

    @classmethod
    def get_date(cls,data_as_string):
    year,month,day = map(int,data_as_string.split('-'))
    date1 = cls(year,month,day)
    return date1


    def out_date(self):
    print('year :',self.year)
    print('month :',self.month)
    print('day :', self.day)

    t = Date_test.get_date('2018-7-6')
    t.out_date()
    t1 = Date_test(2018)
    t1.out_date()

    输出: 

    year : 2018
    month : 7
    day : 6
    year : 2018
    month : 0
    day : 0

    这样子使用的好处是:重构类的时候不需要修改构造函数,只需要添加函数方法,然后添加@classmethod 修饰符

  • 相关阅读:
    老杳:2017年中国集成电路产业十大新闻
    RMA退货流程解决方案
    Linux
    vue.js
    NET Core度身定制的AOP框架
    Timeline
    HTTP
    MVC 常用扩展点:过滤器、模型绑定等
    装箱拆箱
    jQuery Tree
  • 原文地址:https://www.cnblogs.com/wudeng/p/9272623.html
Copyright © 2011-2022 走看看