装饰类中的方法函数
在类中一个方法不用对象属性,但使用静态属性,那这个方法就是类方法,被classmethod装饰器装饰的方法,都有一个默认的参数cls,这个参数就是当前类!code
class A: __count = 0 def __init__(self,name): self.name = name self.__add_count() #只要执行init方法实例化对象就会产生调用 __add_count(),从而对静态属性__count操做 @classmethod def __add_count(cls): #私有方法 cls.__count += 1 #让这个方法只能在内部被使用 @classmethod #被classmethod装饰器装饰的方法,都有一个默认的参数,这个参数就是当前类 def show_count(cls): return cls.__count print(A.show_count()) # 0 类调用show_count方法查看类的静态属性 Sheldon = A('Sheldon') # 实例化一个对象 print(Sheldon.show_count()) # 1 对象调用show_count方法查看类的静态属性 能够看出调用类方法,能够用对象调用,也能够使用类调用 可是这个方法默认参数永远是当前类的命名空间,而不是对象的
若是一个类中的方法不使用对象属性也不使用静态属性 -- 静态方法,@staticmethod装饰的这个方法实际上这个方法就是一个普通函数.对象
普通方法 | 类方法 | 静态方法 | |
---|---|---|---|
默认参数 | self | cls | 无 |
操做的变量 | 操做对象属性 | 操做类属性 | 既不操做对象属性,也不操做类属性 |
所属的命名空间 | 类 | 类 | 类 |
调用方法 | 对象 | 类/对象 | 类/对象 |
装饰器 | @classmethod | @staticmethod |
@name.setter 注意,setter 装饰的函数名叫什么,那么在这个函数中绝对不能够对这个函数名同名属性的修改it
@name.deleter 调用方方法进行删除属性io
示例1 from math import pi class Circle: def __init__(self,r): self.r = r @property # 把一个方法假装成属性 def area(self): # 被property装饰器装饰的方法不能传递除self之外的参数 return pi*self.r**2 @property def perimeter(self): return self.r*pi*2 c1 = Circle(5) print(c1.area) c1.r = 10 print(c1.area) 调用的时候不用加()
class Person: def __init__(self,name): self.__name = name # 不让外部随便修改 @property def name(self): return self.__name Sheldon = Person('Sheldon') print(Sheldon.name) #这样写起到不容易被别人修改的做用
property之setter和deleter class Person: def __init__(self,name,height,weight): self.__name=name self.__height=height self.__weight=weight @property def name(self): return '[个人名字是:%s]'%self.__name #用property装饰的方法名.setter @name.setter def name(self,new_name): # if not isinstance(new_name,str): if type(new_name) is not str: raise Exception('改不了') if new_name.startswith('sb'): raise Exception('不能以sb开头') self.__name=new_name # 用property装饰的方法名.deleter @name.deleter def name(self): # raise Exception('不能删') print('删除成功') # del self.__name p=Person('lqz',1.82,70) # print(p.name) # p.name='pppp' # p.name='xxx' #改不了,直接抛一异常 # p.name=999 # p.name='sb_nick' # print(p.name) del p.name print(p.name)