装饰器

#-*- coding:UTF-8 -*-
class C(object):
    @staticmethod
    def f():
        print("runoob")

C.f() #静态方法无序实例化
cobj=C()
cobj.f()#也可以实例化后调用

应用场景:编写类时需要采用很多不同的方式类创建实例,而我们只有一个_init_函数,此时静态方法就派上用场了

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)
    @staticmethod
    def tomorrow():
        t=time.localtime(time.time()+86400)
        return Date(t.tm_year,t.tm_mon,t.tm_mday)

a=Date("1987",11,27)
b=Date.now()
c=Date.tomorrow()

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

import time

class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day

    @calssmethod
    def now(cls):
        t=time.localtime()
        return cls(t.tm_year,t.tm_mon,t.tm_mday)

class EuroDate(Date):
    def __str__(self):#__xx__ 此种写法为Python内建属性方法,最好不要在外部调用
        return "year:%s month:%s day:%s" % (self.year,self.month,self.day)

e=EuroDate.now()
print e 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值