鱼C论坛

 找回密码
 立即注册
查看: 1729|回复: 0

[学习笔记] A-20-属性访问

[复制链接]
发表于 2018-7-18 20:52:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #coding=UTF-8

  2. #知识点总结
  3. """
  4. #coding=UTF-8s

  5. 1.四种跟属性有关的魔法方法:
  6.     1. __getattribute(self, name): 定义当该类的属性被访问时的行为
  7.     2. __getattr__(self, name): 定义当用户试图获取一个不存在的属性的行为
  8.     3. __setattr__(self, name, value): 定义一个属性被设置时的行为
  9.     4. __delattr__(self, name): 定义一个属性被删除时的行为
  10. 注:当访问一个属性时, 会先进入__getattribute__()中, 若属性不存在, 再进入__getattr__()中

  11. 2. 重写__setattr__()时应注意无限递归的问题 ,如下"""

  12. class Rectangle():
  13.     def __init__(self,width=0,height=0):
  14.         self.width = width
  15.         self.height = height

  16.     def __setattr__(self, name, value):
  17.         if name == "square":
  18.             self.width = value
  19.             self.height = value
  20.         else:
  21.             #self.name = value     # 语句运行时会再次触发 __setattr__() 调用,导致无限递归。
  22.              self.__dict__[name] = value
  23.             #super().__setattr__(name, value) #可用,这样定义属性,不会进入__setattr__()中
  24.     def getArea(self):
  25.         return self.width * self.height

  26. r=Rectangle(4,5)
  27. print(r.getArea())
  28. print(r.width,r.height)
  29. r.square=20
  30. print(r.getArea())
  31. print(r.width,r.height)

  32. #3.对于super类, 可用print(dir(super))查看属性,所以当重写__getattr__()时, 如果返回super().__getattr__(name)则会报错

  33. #4.
  34. """
  35. class  Counter:
  36.     def  __init__(self):
  37.         super().__setattr__('count', 0)

  38.     def  __setattr__(self, name, value):
  39.         if  name not in self.__dict__:
  40.             super().__setattr__('count', self.count + 1)
  41.         super().__setattr__(name, value)

  42.     def  __delattr__(self, name):
  43.         super().__setattr__('count', self.count - 1)
  44.         super().__delattr__(name)"""
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 05:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表