python魔法函数

魔法函数

  1. __str__ vs __repr__
    • __str__是类实例化后。print(cls)触发调用,本质是print=>str=>str 调用
    • __repr__ 开发模式下,直接输出cls,会触发__repr__调用
  2. __getitem__、__setitem__、__delitem__
    • 分别对应字典通过方括号取值dict['a'],赋值dict['a'] = 1, 删除del['a']
  3. __contains__
    • 对应 in 操作, key in cls
  4. __iter__、__next__
    • 遍历,分别对应迭代器和生成器
  5. __call__
    • 类的实例化对象调用
    • example
      class Company(object):
          def __init__(self):
              pass
          def __call__(self, name):
              self.name = name
              print('__call__方法被调用,name:%s' % self.name)
      
      cls = Company()
      cls('华为')
    
  6. __enter__ 、 __exit__
    • 配合使用,对应with语句,with后面的as语句计算完成后,调用enter,然后执行as后面的语句,直至with的上下文结束,调用__exit__

参考资料

  1. python魔法函数
posted @ 2021-09-17 17:11  春树&暮云  阅读(48)  评论(0编辑  收藏  举报