函数装饰器
#装饰器 # @property、@classmethod、@staticmethod # method 方法--函数 由实例化对象调用 # property 伪装属性的方法 由实例化对象调用 # classmethod 类方法 由类调用,只使用类中的静态变量 # staticmethod 静态方法 由类调用,既不会用到对象的属性也不会用到类的属性 #@property 1、将方法伪装成属性;2、修改私有变量且添加处理逻辑;3、 # 1、 #圆 半径r 面积S 周长C import cProfile from math import pi class Circle: def __init__(self, r): self.r = r def S(self): return self.r**2*pi @property def C(self): return 2*pi*self.r cir = Circle(5) print(cir.r)# 5 print(cir.S())# 78.53981633974483 带括号是调用方法 print(cir.S)# 去掉括号当变量调用时打印对象 <bound method Circle.S of <__main__.Circle object at 0x7ff01f892fd0>> print(cir.C)# 31.41592653589793 用@property 装饰后方法伪装成属性 # 2、修改私有变量且添加处理逻辑 class Person: def __init__(self, name): self.__name = name @property def name(self): return self.__name Jerry = Person('Jerry') print(Jerry.name)# Jerry # Jerry.name = 111 # 伪装变量不能修改 class P: def __init__(self, name): self.__name = name @property def name(self): return self.__name @name.setter# 方法名.setter 三个方法名必须一致 def name(self, new): if type(new) is str: self.__name = new P = P('Jerry') print(P.name)# Jerry P.name = 'aaa' print(P.name)# aaa # 3、伪装属性删除 class Demo: def __init__(self, path): self.__f = open(path, 'w') @property def f(self): return self.__f @f.deleter def f(self): self.close() del self.__f def write(self, content): self.f.write(content) def close(self): self.f.close() obj = Demo('1.txt') obj.write('test') obj.close() del obj.f # f被删除 # print(obj.f) #@classmethod class shop: __discount = 0.8 def __init__(self, price): self.__price = price @property def price(self): return round(self.__price * shop.__discount, 2) @price.setter def price(self, new_price): self.__price = new_price @classmethod def change_discount(cls, new_discount):# cls 指引用当前类 shop.__discount = new_discount @staticmethod def stat(name, count):# 没有self,不依赖类, @staticmethod 装饰可以不用,但规范还是建议使用 name = name count = count print(name, count) shop.change_discount(1)# 被classmethod 装饰后可直接被调用 s = shop(10) print(s.price) shop.stat('pig', 10)# 静态方法可以直接调用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言