鱼C论坛

 找回密码
 立即注册
查看: 1945|回复: 1

[技术交流] 《零基础入门学习python》045笔记:魔法方法—属性访问

[复制链接]
发表于 2017-9-19 11:43:39 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 汪蛋 于 2017-9-19 11:46 编辑

知识点一:优雅地访问属性:gtrattr
  1. class C():
  2.     def __init__(self):
  3.         self.x = 'X-man'

  4. >>> c = C()
  5. >>> c.x
  6. 'X-man'
  7. >>> getattr(c, 'y', '没有这个属性')
  8. '没有这个属性'
复制代码

知识点二:优雅地访问属性:property
  1. class C():
  2.     def __init__(self, size=10):
  3.         self.size = size
  4.     def getSize(self):
  5.         return self.size
  6.     def setSize(self, value):
  7.         self.size = value
  8.     def delSize(self):
  9.         del self.size
  10.     x = property(getSize, setSize, delSize)

  11. >>> c = C()
  12. >>> c.x
  13. 10
  14. >>> c.x = 1
  15. >>> c.x
  16. 1
  17. >>> c.size
  18. 1
  19. >>> del c.x
  20. >>> c.size
  21. Traceback (most recent call last):
  22.   File "<pyshell#14>", line 1, in <module>
  23.     c.size
  24. AttributeError: 'C' object has no attribute 'size'
复制代码

知识点三:魔法方法的属性访问
  1. class C():
  2.     def __getattribute__(self, name):
  3.         print("getattribute")
  4.         return super().__getattribute__(name)
复制代码

知识点四:小程序练习
  1. class Rectangle:
  2.     def __init__(self, width=0, height=0):
  3.         self.width = width
  4.         self.height = height

  5.     def __setattr__(self, name, value):
  6.         if name == 'square':
  7.             self.width = value
  8.             self.height = value
  9.         else:
  10.             super().__setattr__(name, value)
  11.             #或者super这一条语句换成下面
  12.             #self.__dict__[name] = value
  13.             #如果写成self.name = value就会进入死循环
  14.             
  15.     def getArea(self):
  16.         return self.width * self.height

  17. >>> r1 = Rectangle()
  18. >>> r1.getArea()
  19. 0
  20. >>> r1 = Rectangle(2, 3)
  21. >>> r1.getArea()
  22. 6
  23. >>> r1.square = 10
  24. >>> r1.width
  25. 10
  26. >>> r1.height
  27. 10
  28. >>> r1.getArea()
  29. 100
  30. >>> r1.__dict__
  31. {'width': 10, 'height': 10}
复制代码

生气,知识点三的程序居然被吃了,截图叭,懒惰了.PNG
暴风截图20179198546998.jpg
暴风截图20179197972384.jpg

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-10-14 15:58:37 | 显示全部楼层
感谢楼主
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-8 19:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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