python魔术方法
2019-06-30 16:11
176 查看
python魔术方法
魔术方法是指:在特定的条件下自行调用的方法。
一、运算方法
# 例如 class A: def __init__(self, a): self.a = a def __add__(self, other): # 在遇到“+”时,自动调用该方法 print(self.a+other.a) b = A(4) c = A(6) b + c # 运行结果 10
1.1 其他运算方法
二、str方法和repr方法
str方法和repr方法,都是在直接打印实例对象时自动执行的方法。
# 例如 class A: def __str__(self): return "我是str方法" def __repr__(self): return "我是repr方法" a = A() print(a) # 我是str方法 # 两个方法同时存在,执行str方法
对使用者应使用str,对开发者应使用repr
三、call方法
call方法可以让实例像函数一样可直接调用
# 例如 class A: def __call__(self, *args, **kwargs): print("我是call方法") a = A() a() # 我是call方法
四、new方法
在封装的实例数据一样时,使用new方法可节省内存
# __new__ class Earth: def __new__(cls, *args, **kwargs): if not hasattr(cls, 'instance'): # 如果我的类没有实例对象,那我就去new一个实例对象 cls.instance = super().__new__(cls) return cls.instance def __init__(self): self.name = 'earth' e = Earth() print(e) # <__main__.Earth object at 0x000001DA469EDDD8> a = Earth() print(a) # <__main__.Earth object at 0x000001DA469EDDD8> # 类每次实例化时都会新建一个对象,并在内存里开辟一个空间存放对象 # 通过__new__可以实现不管实例多少次,始终都是同一个对象 # __new__方法是在__init__之前执行的 # 单例模式 # 1.适用情况:当所有实例中封装的数据都相同时(可视为同一个实例),此时可以考虑单例模式 # 2.案例:数据库连接池
五、其他魔术方法
相关文章推荐
- python魔术方法
- python基础(基本的序列和映射协议(容器类型相关魔术方法))
- Python魔术方法
- python3 所有魔术方法
- Python所有特殊方法, 魔术方法, 钩子
- python 中的魔术方法,fluent python读书笔记1
- Python学习笔记1:数据模型和特殊方法(魔术方法)
- Python-所有特殊方法、魔术方法、钩子
- Python魔术方法-Magic Method
- Python魔术方法
- Python 魔术方法指南
- python3 魔术方法(magic methods)
- python_魔术方法
- Python学习【魔术方法】
- Python3中魔术方法 _ _init_ _方法
- Python 魔术方法指南
- Python 魔术方法及调用方式
- python面向对象开发3 (内部类-构造-析构)魔术方法)
- python_魔术方法-属性相关
- Python学习笔记:魔术方法详解