内置装饰器函数 只在面向对象使用 把方法当初属性使用(方法不加参数) 例子: class Rectangle: def __init__(self,long,wide,color): self.long = long self.wide = wide self.__color = color @property def area(self): return long*wide @property def color(self): return self.__color @color.setter def color(self,new_color): self.__color = new_color @color.deleter def color(self): del self.__color r = Rectangle(10,20,‘green‘) print(r.area) r.color = ‘red‘ del r.color
#classmothed #把一个方法变成类中的方法,这个方法可以直接被类调用,不需要依托任何对象 #当这个方法的操作只设计静态属性的时候,就该使用classmothed 例子: class Person: __type = ‘Animal‘ @classmothed def getType(cls): return cls.__type = ‘Animal‘
静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,主要是一些逻辑属于类,但是和类本身没有交互,即在静态方法中,不会涉及到类中的方法和属性的操作。可以理解为将静态方法存在此类的名称空间中。事实上,在python引入静态方法之前,通常是在全局名称空间中创建函数。 例子: import time class TimeTest(object): def __init__(self,hour,minute,second): self.hour = hour self.minute = minute self.second = second @staticmethod def showTime(): return time.strftime("%H:%M:%S", time.localtime()) print(TimeTest.showTime()) t = TimeTest(2,10,10) nowTime = t.showTime() print(nowTime) 使用静态函数,既可以将获得时间的函数功能与实例解绑,我想获得当前时间的字符串时,并不一定需要实例化对象,此时更像是一种名称空间。
原文:https://www.cnblogs.com/walthwang/p/10402876.html