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 修饰符

  • 相关阅读:
    VMware虚拟机安装
    代码搜索的终极武器Ag
    模糊搜索神器fzf
    Python:json、xml、字典各种转换
    03-azkaban安装部署
    linux下环境变量PATH设置错误的补救
    01-编译azkaban
    VMware安装CentOS7
    PS(二)
    等待公交车的时间
  • 原文地址:https://www.cnblogs.com/wudeng/p/9272623.html
Copyright © 2011-2022 走看看