Python魔术方法
2019-06-28 16:44
176 查看
Python魔术方法
在python中,魔术方法遵循统一的模式——将下划线放到方法的名称的两端。例如在类的实例在初始化的时候,将会执行__init__方法。
class MyClass(object): def __init__(self): print("The __init__ method is running") In [2]: MyClass() The __init__ method is running Out[2]: <__main__.MyClass at 0x184fb420be0>
可以看出我们并没有直接去调用这个__init__方法,而是我们在创建类的实例的时候python解释器自动去调用该方法。
我们也可以从其他方法例如__eq__方法中看一下。
In [3]: class MyClass(object):^M ...: def __init__(self):^M ...: print("The __init__ method is running")^M ...: ^M ...: def __eq__(self, other):^M ...: return type(self) == type(other) ...: In [4]: a=MyClass() The __init__ method is running In [5]: b=MyClass() The __init__ method is running In [6]: a=b In [7]: a==b Out[7]: True In [8]: a==41 Out[8]: False
我们可以看出这是我们定义的方法,比如我们现在进行一些修改(比如让他对于不等于int类型的时候才算正确)。
class MyClass(object): def __init__(self): print("The __init__ method is running") def __eq__(self, other): return type(self) != type(12) In [21]: MyClass()=="12" The __init__ method is running Out[21]: True
可以看出其实定义成功了。
我们现在再定义一个骰子类,调用时不需要任何参数。
class Dice(object): def __init__(self, sides=6): self._sides = sides def roll(self): return random.randint(1, self._sides) In [36]: Dice().roll() Out[36]: 1 In [37]: Dice().roll() Out[37]: 2 In [38]: Dice().roll() Out[38]: 3
而__new__方法基本都在__init__方法之前执行的,用于创建类的实例。实际应用中无需定义__new__方法,一是用不到,二是该方法在python中的内置实现已经足够了。
__del__方法
在对象被销毁的时候调用。python的内存管理机制能够很好的实现这项工作。也可以使用del 关键字来主动进行销毁。
class Del(object): def __del__(self): print("爷走了,被删除了,再见") In [45]: x=Del() In [46]: del x 爷走了,被删除了,再见
魔术方法不止这些,但是相对而言,用到的次数不会特别多,因此这里就大概介绍到这里。
相关文章推荐
- python 理解_str_魔术方法
- python类:magic魔术方法
- Python魔术方法
- Python对象管理 or 魔术方法
- Python魔术方法详解
- python3 魔术方法(magic methods)
- Python学习【魔术方法】
- python类:magic魔术方法
- Python 中的魔术方法详解
- Python 魔术方法小结
- Python中的魔术方法详解2
- Python 魔术方法指南
- Python 魔术方法指南
- python中类的魔术方法
- Python魔术方法详解
- Python基础 面向对象常用魔术方法
- python魔术方法详解
- python魔术方法
- Python 魔术方法指南
- Python 魔术方法指南