python magic method
来源:互联网 发布:java 监听器 编辑:程序博客网 时间:2024/05/16 05:18
A Guide to Python's Magic Methods
Copying
Sometimes, particularly when dealing with mutable objects, you want to be able to copy an object and make changes without affecting what you copied from. This is where Python's copy
comes into play. However (fortunately), Python modules are not sentient, so we don't have to worry about a Linux-based robot uprising, but we do have to tell Python how to efficiently copy things.
__copy__(self)
- Defines behavior for
copy.copy()
for instances of your class.copy.copy()
returns a shallow copy of your object -- this means that, while the instance itself is a new instance, all of its data is referenced -- i.e., the object itself is copied, but its data is still referenced (and hence changes to data in a shallow copy may cause changes in the original). __deepcopy__(self, memodict={})
- Defines behavior for
copy.deepcopy()
for instances of your class.copy.deepcopy()
returns a deep copy of your object -- the object and its data are both copied.memodict
is a cache of previously copied objects -- this optimizes copying and prevents infinite recursion when copying recursive data structures. When you want to deep copy an individual attribute, callcopy.deepcopy()
on that attribute withmemodict
as the first argument.
What are some use cases for these magic methods? As always, in any case where you need more fine-grained control than what the default behavior gives you. For instance, if you are attempting to copy an object that stores a cache as a dictionary (which might be large), it might not make sense to copy the cache as well -- if the cache can be shared in memory between instances, then it should be.
- python magic method
- Python魔术方法-Magic Method
- Python(十)Python 的 Magic Method
- Python 魔术方法(Magic Method)
- Python 魔术方法(Magic Method)
- magic method
- 草根学Python(十)Python 的 Magic Method
- 飘逸的python - 什么是魔术方法(magic method)
- PHP Magic Method
- pythone magic method 大合辑
- magic method(php_day002)
- The magic of method pointers
- 一个python实现的有魔法方法(magic method)的单链表(静态链表)
- python magic methods
- Magic words in Python
- python magic文档
- python中的magic方法
- Python的method, class method, static method
- hibernate session的flushMode的区别
- struts2使用action方式实现文件下载(支持中文文件名)
- Eclipse中10个最有用的快捷键
- C/C++函数的调用约定(MS VC)
- Android Intent Action 大全
- python magic method
- 如果恢复搞活搞活
- 五险一金,终于懂了,你懂吗(不看以后准吃亏
- JDK API 中英文版 在线版、下载地址
- 九度:1013<开门人>
- Java 线程同步异步学习
- Android入门(一)搭建开发环境
- pcduino改caps为esc以及重新划定空间
- 单链表反转(递归和非递归)