zoukankan      html  css  js  c++  java
  • python staticmethod and classmethod方法

    静态方法无绑定,和普通函数使用方法一样,只是需要通过类或者实例来调用。没有隐性参数。

    实例方法针对的是实例,类方法针对的是类,他们都可以继承和重新定义,而静态方法则不能继承,可以认为是全局函数。

    #https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods
    class Date:
        def __init__(self,month,day,year):
            self.month = month
            self.day = day
            self.year = year
        def display(self):
            return "parent class {0}-{1}-{2}".format(self.month,self.day,self.year)
        @staticmethod
        def smil(month,day):
            return Date(month,day,2015)
    
        @classmethod
        def cmil(self,month,day):
            return self(month,day,2015)
    
    class DateSub(Date):
        def display(self):
            return "subclass {0}-{1}-{2}".format(self.month,self.day,self.year)
    
    new_year = Date(1,1,2016)
    mi_new_year = Date.smil(1,2)
    
    print(new_year.display())
    print(mi_new_year.display())
    
    print(isinstance(new_year,Date))
    print(isinstance(mi_new_year,Date))
    
    print("-"*40)
    dateSub1=DateSub(10,19,2017)
    dateSub2 =DateSub.smil(10,10)
    dateSub3 =DateSub.cmil(10,11)
    print(dateSub1.display())
    print(dateSub2.display())
    print(dateSub3.display())
    
    print("isinstance(dateSub1,DateSub) = %s " % isinstance(dateSub1,DateSub))
    print("isinstance(dateSub2,DateSub) = %s " % isinstance(dateSub2,DateSub)) #subclass create plain Date object
    print("isinstance(dateSub2,Date) = %s " % isinstance(dateSub2,Date))
    print("isinstance(dateSub3,DateSub) = %s " % isinstance(dateSub3,DateSub))
    
    print("-"*40)
    print Date.display
    print Date.smil
    print Date.cmil
    print Date.cmil(1,1)
    View Code

  • 相关阅读:
    Linux服务器免密登录设置
    Docker 批量停止、删除容器和镜像
    python破解wifi密码
    python调用paramiko模块连接服务器
    Docker搭建redis-cluster集群三主三备
    Centos7.7搭建Prometheus2.0+Grafana监控Docker容器
    Centos7.7部署fastdfs分布式文件系统
    拉取git代码仓库项目到本地
    Seafile对接Amazon S3存储后端
    Centos7.x部署SeaFile私有网盘
  • 原文地址:https://www.cnblogs.com/lxk613/p/4899160.html
Copyright © 2011-2022 走看看