鱼C论坛

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

[技术交流] 零基础入门学习Python 第41讲 魔法方法 构造与析构

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

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

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

x
  1. 课堂笔记:
  2.   1. __init__函数,是初始化数据的函数,不是第一个调用的,返回None,返回其他会报错.
  3.   2. __new__函数,是第一个调用的,继承的父类属性不可修改(不可用init时),使用__new__先修改,然后传到父类的__new__里面.
  4.   3. __del__函数,__del__是在没有变量指向自己的时候被调用.

  5. 测试题:
  6. 0.
  7. 变量前后都有__的函数
  8. 1.
  9. __new__():,它的第一个参数不是self而是这个类cls,而他的参数会传给init
  10. 2.
  11. 当类里有数据需要初始化的时候.
  12. 3.
  13. __init__不能返回除None以外的值.
  14. 4.
  15. 当没有变量指向指向这个类时.

  16. 动动手:
  17. 0.
  18. class FileObject():
  19. def __del__(self):
  20. self.f.close()
  21. 1.
  22. class C2F():
  23.     def __new__(cls,temp):
  24.         return temp * 1.8 +32
  25. 2.
  26. class Nint(int):
  27.     def __new__(cls,temp):
  28.         if isinstance(temp,str):
  29.             total = 0
  30.             for each in temp:
  31.                 total += ord(each)
  32.         temp = total
  33.         return int.__new__(cls,total)
  34. 3.
  35. class Nstr():
  36.     def __new__(cls,temp):
  37.         s = str(temp)
  38.         total = 0
  39.         for each in s:
  40.             total += ord(each)
  41.         return total
复制代码

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-19 07:58

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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