动态的增强函数功能. 接收函数,处理后,返回新函数 def check_str(func): def inner(*args, **kwargs): result = func(*args, **kwargs) if result == "ok": return f'result is {result}' else: return f'result is faild:{result}' return inner @check_str def test(data): return data result = test('no') print(result) 类的装饰器 class Stu(object): # def __init__(self, name): # self.__name = name def __init__(self): print("this") # 无需实例化,直接使用 # classmethod 内部不能调用 self的函数 @classmethod def run(cls): print("run") cls.sleep() def play(self): print("play") self.run() self.sleep() # staticmethod装饰器无需cls和 self. 直接调用或实例化后调用,都可以. 不能调用cls或self的方法 @staticmethod def sleep(): print("sleep") # 将类函数的执行免去().不能直接传参. 传参通过.setter @property def name(self): return self.__name # 修改@property的值.只能有一个值 @name.setter def name(self, value): self.__name = value def __setattr__(self, key, value): print(key, value) self.__dict__[key] = value print(self.__dict__) def __call__(self, *args): print(f'{args}') class Student(Stu): def __init__(self): # Student当前类 self类的实例.python3 可以省略super里面的内容 __init__()使用父类的方法. super(Student, self).__init__() student = Student() student.play() # Stu.run() # Stu.sleep() # s = Stu("小仙紫") s = Stu() print(s) # result = s.name # print(result) s.name = "紫颜" print(s.name) s()