Python 类的魔术方法(定制类)
今天一整个上午学习了一下Python中的双下划线方法(魔术方法)。这些方法的功能非常强大,也能使Python代码可读性更高,更加Pythonic。这篇文章包含了很多魔术方法,包括: __init__ __str__, __repr__ __iter__, __getitem__, __len__ __eq__, __lt__ __add__, __radd__ __call__ __enter__, __exit__ 运行环境:Python3.6 + Jupyter notebook。 下面就是 Jupyter notebook 笔记。 Python 类的魔术方法(定制类) ¶ __init__ ¶ In [3]: class Account : 'A simple account class' def __init__ ( self , owner , amount = 0 ): self . owner = owner self . amount = amount self . _transactions = [] In [4]: acc1 = Account ( 'zxzhu' ) acc1 Out[4]: <__main__.Account at 0x1e4581f96a0> 注:构造函数使我们可以从类中创建实例。 __str__, __repr__ ¶ In [5]: