鱼C论坛

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

[技术交流] 零基础入门学习Python 第 42 讲 魔法方法 算术运算

[复制链接]
发表于 2018-4-10 10:19:11 | 显示全部楼层 |阅读模式

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

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

x
  1. 课堂笔记:
  2.   1. int() str() 等这种类型是工厂函数,实质是类对象.
  3.   2. + __add__,- __sub__,* __mul__,/ __truediv__,// __floordiv__,% __mod__,__divmod__,** __pow__(self,other[,modulo]),<< __lshift__,>> __rshift__,&__and__,^ __xor__,| __or__.
  4.   3. 改写函数,注意,self,other可以看做实例化后的a,b.ab的方法都可以在改写的过程中用到.

  5. 测试题:
  6. 0.
  7. 工厂函数就是类对象
  8. 1.
  9. __add__(self,other)方法
  10. 2.
  11. 母鸡噢
  12. 类的属性和方法名不能一样,否则在调用方法的时候会调用属性(),从而报错.
  13. 3.
  14. + __add__
  15. - __sub__
  16. * __mul__
  17. / __truediv__
  18. // __floordiv__
  19. % __mod__
  20. divmod(a,b) __divmod__
  21. ** __pow__
  22. << __lshift__
  23. >> __rshift__
  24. & __and__
  25. | __or__
  26. ^ __xor__
  27. 4.
  28. 面向对象的编程?
  29. 支持'鸭子类型'

  30. 动动手:
  31. 0.
  32. class Nstr(str):
  33.     def __sub__(self,other):
  34.         s = str(self)
  35.         o = str(other)
  36.         while o in s:
  37.             s = s.strip(o)
  38.             print(s,o)
  39.         return s
  40. 1.
  41. class Nstr(str):
  42.     def __lshift__(self,other):
  43.         s = str(self)
  44.         o = int(other)
  45.         return s[o:] + s[:o]
  46.     def __rshift__(self,other):
  47.         s = str(self)
  48.         o = int(other)
  49.         return s[-o:] + s[:-o]
  50. 2.
  51. class Nstr():
  52.     def __new__(cls,temp):
  53.         s = str(temp)
  54.         total = 0
  55.         for each in s:
  56.             total += ord(each)
  57.         return total
复制代码

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-20 20:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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