静态方法和类方法

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()

 

posted @ 2018-02-22 15:44  隔壁古二蛋  阅读(125)  评论(0编辑  收藏  举报