• 静态方法和类方法


    import types,time
    from functools import wraps
    
    class Test:
        name = 'test'
        data = 'this is data'
        # 普通方法,可以访问类属性,实例属性
        def normalMethod(self, name):
            print(self.data, name)
    
        # 类方法,可以访问类属性
        @classmethod
        def classMethod(cls, name):
            print(cls.data, name)
    
        # 静态方法,不可以访问类属性
        @staticmethod
        def staticMethod(name):
            print(name)
    
    t = Test()
    t.normalMethod('normal')
    t.classMethod('class')
    t.staticMethod('static')
    #
    Test.classMethod('class')
    Test.staticMethod('static')

     

    静态方法的作用类似于c#中的静态方法,一般是把整个类定义为静态类,作为工具类使用,其中所有的方法都为静态方法,主要为了管理代码

    类方法传入类本身,即可以在原本类的基础上添加功能

    class Date_test:
        def __init__(self,year=0,month=0,day=0):
            self._year = year
            self._month = month
            self._day = day
    
        @classmethod
        def get_date(cls,string_date):
            #cls表示类
            year,month,day = map(int,string_date.split('-'))
            date = cls(year,month,day)
            return date
    
        def out_date(self):
            print(self._year,self._month,self._day,sep='|')
    
    d = Date_test.get_date('2018-2-22')
    d.out_date()
  • 相关阅读:
    随机生成30道四则运算题目
    《构建之法》阅读笔记01
    第一周学习进度
    个人介绍
    MyBatis(登录)
    MyBatis
    动态网页
    网页基本标签
    Servlet基础
    JSP数据交互
  • 原文地址:https://www.cnblogs.com/cx59244405/p/8459107.html
Copyright © 2020-2023  润新知