当前位置: 首页 > 网络知识

Python基础入门学习笔记 045 魔法方法:属性访问

时间:2026-01-29 09:25:51

属性访问

•__getattr__(self, name)

–定义当用户试图获取一个不存在的属性时的行为

•__getattribute__(self, name)

–定义当该类的属性被访问时的行为

•__setattr__(self, name, value)

–定义当一个属性被设置时的行为

•__delattr__(self, name)

–定义当一个属性被删除时的行为

实例1:

1 class C: 2 def __getattribute__(self, name): 3 print('getattribute') 4 # 使用 super() 调用 object 基类的 __getattribute__ 方法 5 return super().__getattribute__(name) 6 7 def __setattr__(self, name, value): 8 print('setattr') 9 super().__setattr__(name, value) 10 11 def __delattr__(self, name): 12 print('delattr') 13 super().__delattr__(name) 14 15 def __getattr__(self, name): 16 print('getattr') 17 18 >>> c = C() 19 >>> c.x 20 getattribute 21 getattr 22 >>> c.x = 1 23 setattr 24 >>> c.x 25 getattribute 26 1 27 >>> del c.x 28 delattr 29 >>> setattr(c,'y','Yellow') 30 setattr

练习要求

•写一个矩形类,默认有宽和高两个属性;

•如果为一个叫square的属性赋值,那么说明这是一个正方形,值就是正方形的边长,此时宽和高都应该等于边长。

实例2:

1 class Rectangle: 2 def __init__(self, width=0, height=0): 3 self.width = width 4 self.height = height 5 6 def __setattr__(self, name, value):#一发生赋值操作,则会触发__setattr__()魔法方法 7 if name == 'square':#判断name属性是否为正方形 8 self.width = value 9 self.height = value 10 else: 11 self.__dict__[name] = value 12 13 def getArea(self): 14 return self.width * self.height 15 16 >>> r1 = Rectangle(4,5) 17 >>> r1.getArea() 18 20 19 >>> r1.square = 10 20 >>> r1.getArea() 21 100



上一篇:Python基础入门学习笔记 033 异常处理:你不可能总是对的2
下一篇:Python基础入门学习笔记 037 类和对象:面向对象编程
python
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素