您的位置:首页 > 编程语言 > Python开发

Python魔术方法

2019-03-01 22:06 471 查看
版权声明:本文为博主原创,转载请注明出处,谢谢! https://blog.csdn.net/qq_35531549/article/details/88069663

Python 魔术方法

  1. __str__
    格式化输出对象

  2. __init__
    __new__

      __new__
      创建一个实例,并返回类的实例
    • __init__
      初始化实例,无返回值
    • __new__
      是一个类方法 单例模式
      class A(object):
      '''单例模式'''
      obj = None
      def __new__(cls, *args, **kwargs):
      if cls.obj is None:
      cls.obj = object.__new__(cls)
      return cls.obj
  3. 数学运算、比较运算

      运算符重载

      +
      :
      __add__(value)
    • -
      :
      __sub__(value)
    • *
      :
      __mul__(value)
    • /
      :
      __truediv__(value)
      (Python 3.x),
      __div__(value)
      (Python 2.x)
    • //
      :
      __floordiv__(value)
    • %
      :
      __mod__(value)
    • &
      :
      __and__(value)
    • |
      :
      __or__(value)
  4. 练习: 实现字典的

    __add__
    方法, 作用相当于 d.update(other)

    class Dict(dict):
    def __add__(self, other):
    if isinstance(other, dict):
    new_dict = {}
    new_dict.update(self)
    new_dict.update(other)
    return new_dict
    else:
    raise TypeError('not a dict')
  5. 比较运算符的重载

      ==
      :
      __eq__(value)
    • !=
      :
      __ne__(value)
    • >
      :
      __gt__(value)
    • >=
      :
      __ge__(value)
    • <
      :
      __lt__(value)
    • <=
      :
      __le__(value)

    例: 完成一个类, 实现数学上无穷大的概念

    class Inf:
    def __lt__(self, other):
    return False
    def __le__(self, other):
    return False
    def __ge__(self, other):
    return True
    def __gt__(self, other):
    return True
    def __eq__(self, other):
    return False
    def __ne__(self, other):
    return True
    ```
  6. 容器方法

      __len__
      -> len
    • __iter__
      -> for
    • __contains__
      -> in
    • __getitem__
      string, bytes, list, tuple, dict
      有效
    • __setitem__
      list, dict
      有效
  7. 可执行对象:

    __call__

  8. 上下文管理 with:

      __enter__
      进入
      with
      代码块前的准备操作
    • __exit__
      退出时的善后操作
    • 文件对象、线程锁、socket 对象 等 都可以使用 with 操作
    • 示例
      class A:
      def __enter__(self):
      return self
      
      def __exit__(self, Error, error, traceback):
      print(args)
  9. __setattr__, __getattribute__, __getattr__, __dict__

      内建函数:

      setattr(), getattr(), hasattr()

    • 常用来做属性监听

      class User:
      '''TestClass'''
      z = [7,8,9]
      def __init__(self):
      self.money = 10000
      self.y = 'abc'
      
      def __setattr__(self, name, value):
      if name == 'money' and value < 0:
      raise ValueError('money < 0')
      print('set %s to %s' % (name, value))
      object.__setattr__(self, name, value)
      
      def __getattribute__(self, name):
      print('get %s' % name)
      return object.__getattribute__(self, name)
      
      def __getattr__(self, name):
      print('not has %s' % name)
      return -1
      
      def foo(self, x, y):
      return x ** y
      
      # 对比
      a = A()
      print(A.__dict__)
      print(a.__dict__)
  10. 槽:

    __slots__

      固定类所具有的属性

    • 实例不会分配

      __dict__

    • 实例无法动态添加属性

    • 优化内存分配

      class A:
      __slots__ = ('x', 'y')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: