鱼C论坛

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

[技术交流] python 043 魔法方法之算术运算2

[复制链接]
发表于 2018-7-5 14:29:13 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 风不会停息 于 2018-7-5 14:37 编辑

1. python 魔法方法详解: http://bbs.fishc.com/thread-48793-1-1.html

2. 对于反运算的魔法方法, 例如__radd__, a + b, 当a对象没有__add__方法时, b对象才会调用__radd__:

  1. >>> class Nint(int):
  2.         def __radd__(self, other):
  3.                 print("__radd__ 被调用了!")
  4.                 return int.__add__(self, other)

  5. >>> a = Nint(5)
  6. >>> b = Nint(3)
  7. >>> a + b
  8. 8
  9. >>> 1 + b
  10. __radd__ 被调用了!
  11. 4
复制代码


3. 在继承的类中调用基类的方法, 使用super()

4. 对于修饰符@staticmethod, 表示紧跟的一个方法为静态方法, 静态方法不会绑定到实例对象上, 可以节省开销, 所以定义静态方法时不需要传入self参数, 当对象访问时也不会传入self参数, 例如:

  1. class C:
  2.         @staticmethod  # 该修饰符表示 static() 是静态方法
  3.         def static(arg1, arg2, arg3):
  4.                 print(arg1, arg2, arg3, arg1 + arg2 + arg3)

  5.         def nostatic(self):
  6.                 print("I'm the f**king normal method!")
复制代码

  1. >>> c1 = C()
  2. >>> c2 = C()
  3. # 静态方法只在内存中生成一个,节省开销
  4. >>> c1.static is C.static
  5. True
  6. >>> c1.nostatic is C.nostatic
  7. False
  8. >>> c1.static
  9. <function C.static at 0x03001420>
  10. >>> c2.static
  11. <function C.static at 0x03001420>
  12. >>> C.static
  13. <function C.static at 0x03001420>
  14. # 普通方法每个实例对象都拥有独立的一个,开销较大
  15. >>> c1.nostatic
  16. <bound method C.nostatic of <__main__.C object at 0x03010590>>
  17. >>> c2.nostatic
  18. <bound method C.nostatic of <__main__.C object at 0x032809D0>>
  19. >>> C.nostatic
  20. <function C.nostatic at 0x0328D2B8>
复制代码

  1. >>> c1.static(1, 2, 3)
  2. 1 2 3 6
  3. >>> C.static(1, 2, 3)
  4. 1 2 3 6
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-26 22:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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