zoukankan      html  css  js  c++  java
  • @classmethod

    @classmethod

    类方法是给类用的,类在使用时会将类本身当做参数传给类方法的第一个参数,python为我们内置了函数classmethod来把类中的函数定义成类方法

    复制代码
    class A:
        x=1
        @classmethod
        def test(cls):
            print(cls,cls.x)
    
    class B(A):
        x=2
    B.test()
    
    '''
    输出结果:
    <class '__main__.B'> 2
    '''
    复制代码

    应用场景:

    复制代码
    import time
    class Date:
        def __init__(self,year,month,day):
            self.year=year
            self.month=month
            self.day=day
        @staticmethod
        def now():
            t=time.localtime()
            return Date(t.tm_year,t.tm_mon,t.tm_mday)
    
    class EuroDate(Date):
        def __str__(self):
            return 'year:%s month:%s day:%s' %(self.year,self.month,self.day)
    
    e=EuroDate.now()
    print(e) #我们的意图是想触发EuroDate.__str__,但是结果为
    '''
    输出结果:
    <__main__.Date object at 0x1013f9d68>
    '''
    复制代码

    因为e就是用Date类产生的,所以根本不会触发EuroDate.__str__,解决方法就是用classmethod

    复制代码
    import time
    class Date:
        def __init__(self,year,month,day):
            self.year=year
            self.month=month
            self.day=day
        # @staticmethod
        # def now():
        #     t=time.localtime()
        #     return Date(t.tm_year,t.tm_mon,t.tm_mday)
    
        @classmethod #改成类方法
        def now(cls):
            t=time.localtime()
            return cls(t.tm_year,t.tm_mon,t.tm_mday) #哪个类来调用,即用哪个类cls来实例化
    
    class EuroDate(Date):
        def __str__(self):
            return 'year:%s month:%s day:%s' %(self.year,self.month,self.day)
    
    e=EuroDate.now()
    print(e) #我们的意图是想触发EuroDate.__str__,此时e就是由EuroDate产生的,所以会如我们所愿
    '''
    输出结果:
    year:2017 month:3 day:3
    '''
    复制代码

    强调,注意注意注意:静态方法和类方法虽然是给类准备的,但是如果实例去用,也是可以用的,只不过实例去调用的时候容易让人混淆,不知道你要干啥

    复制代码
    x=e.now() #通过实例e去调用类方法也一样可以使用,静态方法也一样
    print(x)
    '''
    输出结果:
    year:2017 month:3 day:3
    '''
     
     
  • 相关阅读:
    11.【原创】Object.keys()的一般用法
    5. 【原创】table设置text-overflow: ellipsis;(超出范围显示...)不生效
    12.【转载】vscode默认常用快捷键
    13.【原创】JS读取apk安装包的信息,做应用上传
    11.【原创】chrom文件上传后,手动释放内存
    26.Mysql "truncate"与"delete"的区别
    25.【转载】Mysql timestamp类型字段的CURRENT_TIMESTAMP与ON UPDATE CURRENT_TIMESTAMP属性
    bof
    ctf Wiener tricky
    分解大素数
  • 原文地址:https://www.cnblogs.com/kongk/p/8644358.html
Copyright © 2011-2022 走看看