• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

python @classmethod

武飞扬头像
漫途测开
帮助1

classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的cls参数,
可以来调用类的属性,类的方法,实例化对象等。
废话不多说,直接上代码
1.简洁调用方式

  1.  
    class TestClass(object):
  2.  
     
  3.  
    def __init__(self, data_str):
  4.  
    self.data_str = data_str
  5.  
     
  6.  
    def get_year(self):
  7.  
    data_list = self.data_str.split('.')
  8.  
    print(data_list[0])
  9.  
     
  10.  
    class TestClass2(object):
  11.  
     
  12.  
    def __init__(self, data_str):
  13.  
    self.data_str = data_str
  14.  
    @classmethod
  15.  
    def get_year(cls, data_str):
  16.  
    data_list = data_str.split('.')
  17.  
    print(data_list[0])
  18.  
     
  19.  
    tc = TestClass('1992.9.2') # 实例化类
  20.  
    tc.get_year() # 再调用类方法
  21.  
    TestClass2.get_year('1992.9.2') # 直接调用类方法
学新通

TestClass 类使用的是普通的成员方法
TestClass2 则使用classmethod修饰方法
可以看到,TestClass2在调用类方法时,不需要实例化类,更加简洁

2.方便扩展功能

请看下面代码

  1.  
    class TestClass(object):
  2.  
    day = ''
  3.  
    month = ''
  4.  
    year = ''
  5.  
    def __init__(self, year='', month='', day=''):
  6.  
    self.day = day
  7.  
    self.month = month
  8.  
    self.year = year
  9.  
    def out_print(self):
  10.  
    print('year: %s month: %s day: %s' %(self.year, self.month, self.day))
  11.  
     
  12.  
    ss = TestClass('2022','10','24')
  13.  
    ss.out_print()

输出 year: 2022 month: 10 day: 24        
这是一个输入三个数字字符串,然后输出年月日的类
现在可能有人觉得输入三个字符串太麻烦了,就想输入一个类似这样的字符串'2022.10.24'
怎么办呢,当然是使用classmethod修饰方法

  1.  
    class TestClass2(object):
  2.  
    day = ''
  3.  
    month = ''
  4.  
    year = ''
  5.  
    def __init__(self, year='', month='', day=''):
  6.  
    self.day = day
  7.  
    self.month = month
  8.  
    self.year = year
  9.  
    @classmethod
  10.  
    def format_date(cls, str_date):
  11.  
    year, month, day = str_date.split('.')
  12.  
    new_date = cls(year, month, day)# 返回一个初始化类对象
  13.  
    return new_date
  14.  
    def out_print(self):
  15.  
    print('year: %s month: %s day: %s' %(self.year, self.month, self.day))
  16.  
    ss = TestClass2.format_date('2022.10.24')
  17.  
    ss.out_print()
学新通

输出 year: 2022 month: 10 day: 24

当然也可以使用继承的方式

  1.  
    class TestClass3(TestClass):
  2.  
    @classmethod
  3.  
    def format_date(cls, str_date):
  4.  
    year, month, day = str_date.split('.')
  5.  
    new_date = cls(year, month, day)
  6.  
    return new_date
  7.  
    tt = TestClass3.format_date('1992.9.2')
  8.  
    tt.out_print()

输出 year: 1992 month: 9 day: 2

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhghbabf
系列文章
更多 icon
同类精品
更多 icon
继续加载