Python魔术方法
2019-03-01 22:06
471 查看
版权声明:本文为博主原创,转载请注明出处,谢谢! https://blog.csdn.net/qq_35531549/article/details/88069663
Python 魔术方法
-
__str__
格式化输出对象 -
__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
-
数学运算、比较运算
运算符重载
+
:__add__(value)
-
:__sub__(value)
*
:__mul__(value)
/
:__truediv__(value)
(Python 3.x),__div__(value)
(Python 2.x)//
:__floordiv__(value)
%
:__mod__(value)
&
:__and__(value)
|
:__or__(value)
-
练习: 实现字典的
__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')
-
比较运算符的重载
==
:__eq__(value)
!=
:__ne__(value)
>
:__gt__(value)
>=
:__ge__(value)
<
:__lt__(value)
<=
:__le__(value)
-
容器方法
__len__
-> len __iter__
-> for__contains__
-> in__getitem__
对string, bytes, list, tuple, dict
有效__setitem__
对list, dict
有效-
可执行对象:
__call__
-
上下文管理 with:
__enter__
进入with
代码块前的准备操作 __exit__
退出时的善后操作- 文件对象、线程锁、socket 对象 等 都可以使用 with 操作
- 示例
class A: def __enter__(self): return self def __exit__(self, Error, error, traceback): print(args)
-
__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__)
-
槽:
__slots__
固定类所具有的属性
-
实例不会分配
__dict__
-
实例无法动态添加属性
-
优化内存分配
class A: __slots__ = ('x', 'y')
例: 完成一个类, 实现数学上无穷大的概念
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 ```
相关文章推荐
- Python面向对象之魔术方法
- Python 中的魔术方法详解
- Python学习笔记1:数据模型和特殊方法(魔术方法)
- [python]魔术方法
- Python入门笔记—第十二章【面向对象之OOP(第六部分,类的常用魔术方法)】
- Python 魔术方法指南
- Python 魔术方法小结
- Python 魔术方法指南
- Python魔术方法详解
- Python很简单?学会魔术方法才算入门!
- Python魔术方法-Magic Method
- Python 魔术方法指南
- Python学习【魔术方法】
- python 魔术方法学习一:__eq__
- python学习(六)----Python魔术方法总结
- Python 魔术方法指南
- Python 魔术方法指南
- python魔术方法之装饰器
- Python魔术方法
- Python魔术方法