鱼C论坛

 找回密码
 立即注册
查看: 819|回复: 7

哪位大佬解释下python魔法方法

[复制链接]
发表于 2019-1-21 11:56:11 | 显示全部楼层
先看两段代码:
  1. class Student(object):
  2.         def __init__(self,name):
  3.                 self.name = name
  4. print(Student('xiao'))
复制代码
  1. <__main__.Student object at 0x000002217177A5F8>
复制代码

再看下面这个:
  1. class Student(object):
  2.         def __init__(self,name):
  3.                 self.name = name
  4.         def __str__(self):
  5.                 return '学生的成绩是:%s' % self.name
  6. print(Student('xiao'))
复制代码
  1. 学生的成绩是:xiao
复制代码



然后我们查看dir(Student):
  1. In [18]: dir(Student)
  2. Out[18]:
  3. ['__class__',
  4. '__delattr__',
  5. '__dict__',
  6. '__dir__',
  7. '__doc__',
  8. '__eq__',
  9. '__format__',
  10. '__ge__',
  11. '__getattribute__',
  12. '__gt__',
  13. '__hash__',
  14. '__init__',
  15. '__le__',
  16. '__lt__',
  17. '__module__',
  18. '__ne__',
  19. '__new__',
  20. '__reduce__',
  21. '__reduce_ex__',
  22. '__repr__',
  23. '__setattr__',
  24. '__sizeof__',
  25. '__str__',
  26. '__subclasshook__',
  27. '__weakref__']
复制代码


所以魔法方法可以理解为类的专有方法,有解释器自动执行,如果没有传参数,我是这莫理解的 ,再问就是编译原理的知识了,打住
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-11-4 15:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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