Home  >  Article  >  Backend Development  >  Introducing the use of magic methods in Python

Introducing the use of magic methods in Python

巴扎黑
巴扎黑Original
2017-08-16 13:24:54992browse

Introduction

In Python, all methods wrapped with "__" double underscores are collectively called "Magic Method", which is called "Magic Method" in Chinese, such as the class initialization method __init__, Python All magic methods in have corresponding descriptions in official documents, but the official descriptions are confusing and loosely organized. It's hard to find an example.

Construction and initialization

Every Pythoner knows one of the most basic magic methods, __init__ . Through this method we can define the initial operation of an object. However, when x = SomeClass() is called, __init__ is not the first method called. In fact, there is also a method called __new__, and the two together form the "constructor".

__new__ is used to create a class and return an instance of this class, while __init__ just initializes the instance with the passed parameters.

At the end of the object life cycle call, the __del__ method will be called, and __del__ can be understood as the "destructor". Let’s take a look at these three methods through code:

from os.path import join
class FileObject:
    '''给文件对象进行包装从而确认在删除时文件流关闭'''
    def __init__(self, filepath='~', filename='sample.txt'):
        #读写模式打开一个文件
        self.file = open(join(filepath, filename), 'r+')
    def __del__(self):
        self.file.close()
        del self.file

Controlling attribute access

Many people who switch to Python from other languages ​​will complain that it lacks real encapsulation of classes. (There is no way to define a private variable and then define public getters and setters). Python can actually complete encapsulation through magic methods. Let’s take a look:

__getattr__(self, name):

Define the behavior when the user attempts to obtain a property that does not exist. This works for retrieving and redirecting common spelling errors, giving a warning when retrieving some deprecated attributes (you can also calculate and give a value if you like) or handling an AttributeError . It will only be returned when calling a property that does not exist.

__setattr__(self, name, value):

Unlike __getattr__(self, name), __setattr__ is an encapsulated solution. Regardless of whether the attribute exists, it allows you to define the assignment behavior to the attribute, so that you can customize the value of the attribute. Avoid "infinite recursion" errors when implementing __setattr__.

__delattr__:

Same as __setattr__, but the function is to delete an attribute instead of setting them. It is also necessary to prevent infinite recursion during implementation.

__getattribute__(self, name):

__getattribute__ defines the behavior when your attribute is accessed. In comparison, __getattr__ only works when the attribute does not exist. Therefore, in Python versions that support __getattribute__, __getattribute__ must be called before calling __getattr__. __getattribute__ also needs to avoid "infinite recursion" errors. It should be reminded that it is best not to try to implement __getattribute__, because this approach is rarely seen and it is easy to cause bugs.

When defining attribute access control, it may easily cause "infinite recursion". For example, the following code:

#  错误用法
def __setattr__(self, name, value):
    self.name = value
    # 每当属性被赋值的时候(如self.name = value), ``__setattr__()`` 会被调用,这样就造成了递归调用。
    # 这意味这会调用 ``self.__setattr__('name', value)`` ,每次方法会调用自己。这样会造成程序崩溃。
#  正确用法
def __setattr__(self, name, value):
    self.__dict__[name] = value  # 给类中的属性名分配值
    # 定制特有属性

Python’s magic method is very powerful, but it needs to be used with caution. It is very important to understand the correct method of use.

Create a custom container

There are many ways to make your Python class behave like the built-in container types, such as our commonly used list, dict, tuple, string, etc. Python's container types are divided into variable types (such as list, dict) and immutable types (such as string, tuple). The difference between variable containers and immutable containers is that once a value is assigned to an immutable container, one of them cannot be modified. elements are modified.

Before talking about creating a custom container, you should first understand the protocol. The protocol here is very similar to the so-called "interface" concept in other languages. It gives you a lot of methods that you have to define. However, protocols in Python are very informal and do not require explicit implementation declarations. In fact, they are more like a guide.

Magic method of custom containers

Let’s take a closer look at the magic methods that may be used to define containers. First, when implementing an immutable container, you can only define __len__ and __getitem__ (more on this below). The mutable container protocol requires all immutable containers, plus __setitem__ and __delitem__ . If you want your object to be iterable, you need to define __iter__ which returns an iterator. Iterators must follow the iterator protocol, which requires __iter__ (returns itself) and next.

__len__(self):

Returns the length of the container. This is all part of the protocol for both mutable and immutable containers.

__getitem__(self, key):

Define the behavior of using self[key] when an item is accessed. This is also part of the protocol for immutable and mutable containers. A TypeError will be raised if the key is of the wrong type; a KeyError will be raised if the key does not have a suitable value.

__setitem__(self, key, value):

When you execute self[key] = value, this method is called.

__delitem__(self, key):

Define the behavior when an item is deleted (such as del self[key]). This is just part of the mutable container protocol. An appropriate exception should be thrown when an invalid key is used.

__iter__(self):

Returns a container iterator. In many cases, an iterator will be returned, especially when the built-in iter() method is called, and when the for x in container: method is used to loop. Iterators are objects themselves, and they must define an __iter__ method that returns self.

__reversed__(self):

  实现当reversed()被调用时的行为。应该返回序列反转后的版本。仅当序列可以是有序的时候实现它,例如对于列表或者元组。

__contains__(self, item):

  定义了调用in和not in来测试成员是否存在的时候所产生的行为。你可能会问为什么这个不是序列协议的一部分?因为当__contains__没有被定义的时候,如果没有定义,那么Python会迭代容器中的元素来一个一个比较,从而决定返回True或者False。

__missing__(self, key):

  dict字典类型会有该方法,它定义了key如果在容器中找不到时触发的行为。比如d = {'a': 1}, 当你执行d[notexist]时,d.__missing__['notexist']就会被调用。

实例

  下面是书中的例子,用魔术方法来实现Haskell语言中的一个数据结构。

# -*- coding: utf-8 -*-
class FunctionalList:
    ''' 实现了内置类型list的功能,并丰富了一些其他方法: head, tail, init, last, drop, take'''
    def __init__(self, values=None):
        if values is None:
            self.values = []
        else:
            self.values = values
    def __len__(self):
        return len(self.values)
    def __getitem__(self, key):
        return self.values[key]
    def __setitem__(self, key, value):
        self.values[key] = value
    def __delitem__(self, key):
        del self.values[key]
    def __iter__(self):
        return iter(self.values)
    def __reversed__(self):
        return FunctionalList(reversed(self.values))
    def append(self, value):
        self.values.append(value)
    def head(self):
        # 获取第一个元素
        return self.values[0]
    def tail(self):
        # 获取第一个元素之后的所有元素
        return self.values[1:]
    def init(self):
        # 获取最后一个元素之前的所有元素
        return self.values[:-1]
    def last(self):
        # 获取最后一个元素
        return self.values[-1]
    def drop(self, n):
        # 获取所有元素,除了前N个
        return self.values[n:]
    def take(self, n):
        # 获取前N个元素
        return self.values[:n]

  其实在collections模块中已经有了很多类似的实现,比如Counter、OrderedDict等等。

反射

  你也可以控制怎么使用内置在函数sisinstance()和issubclass()方法 反射定义魔术方法. 这个魔术方法是:

__instancecheck__(self, instance):

  检查一个实例是不是你定义的类的实例

__subclasscheck__(self, subclass):

  检查一个类是不是你定义的类的子类

  这些魔术方法的用例看起来很小, 并且确实非常实用. 它们反应了关于面向对象程序上一些重要的东西在Python上,并且总的来说Python: 总是一个简单的方法去找某些事情, 即使是没有必要的. 这些魔法方法可能看起来不是很有用, 但是一旦你需要它们,你会感到庆幸它们的存在。

可调用的对象

  你也许已经知道,在Python中,方法是最高级的对象。这意味着他们也可以被传递到方法中,就像其他对象一样。这是一个非常惊人的特性。

  在Python中,一个特殊的魔术方法可以让类的实例的行为表现的像函数一样,你可以调用它们,将一个函数当做一个参数传到另外一个函数中等等。这是一个非常强大的特性,其让Python编程更加舒适甜美。

__call__(self, [args...]):

  允许一个类的实例像函数一样被调用。实质上说,这意味着 x() 与 x.__call__() 是相同的。注意 __call__ 的参数可变。这意味着你可以定义 __call__ 为其他你想要的函数,无论有多少个参数。

  __call__ 在那些类的实例经常改变状态的时候会非常有效。调用这个实例是一种改变这个对象状态的直接和优雅的做法。用一个实例来表达最好不过了:

# -*- coding: UTF-8 -*-
class Entity:
    """
    调用实体来改变实体的位置
    """
def __init__(self, size, x, y):
    self.x, self.y = x, y
    self.size = size
def __call__(self, x, y):
    """
    改变实体的位置
    """
    self.x, self.y = x, y

上下文管理

  with声明是从Python2.5开始引进的关键词。你应该遇过这样子的代码:

with open('foo.txt') as bar:
    # do something with bar

  在with声明的代码段中,我们可以做一些对象的开始操作和退出操作,还能对异常进行处理。这需要实现两个魔术方法: __enter__ 和 __exit__。

__enter__(self):

  定义了当使用with语句的时候,会话管理器在块被初始创建时要产生的行为。请注意,__enter__的返回值与with语句的目标或者as后的名字绑定。

__exit__(self, exception_type, exception_value, traceback):

  定义了当一个代码块被执行或者终止后,会话管理器应该做什么。它可以被用来处理异常、执行清理工作或做一些代码块执行完毕之后的日常工作。如果代码块执行成功,exception_type,exception_value,和traceback将会为None。否则,你可以选择处理这个异常或者是直接交给用户处理。如果你想处理这个异常的话,请确保__exit__在所有语句结束之后返回True。如果你想让异常被会话管理器处理的话,那么就让其产生该异常。

创建对象描述器

  描述器是通过获取、设置以及删除的时候被访问的类。当然也可以改变其它的对象。描述器并不是独立的。相反,它意味着被一个所有者类持有。当创建面向对象的数据库或者类,里面含有相互依赖的属相时,描述器将会非常有用。一种典型的使用方法是用不同的单位表示同一个数值,或者表示某个数据的附加属性。

  为了成为一个描述器,一个类必须至少有__get__,__set__,__delete__方法被实现:

__get__(self, instance, owner):

定义了当描述器的值被取得的时候的行为。instance是拥有该描述器对象的一个实例。owner是拥有者本身

__set__(self, instance, value):

定义了当描述器的值被改变的时候的行为。instance是拥有该描述器类的一个实例。value是要设置的值。

__delete__(self, instance):

定义了当描述器的值被删除的时候的行为。instance是拥有该描述器对象的一个实例。

  下面是一个描述器的实例:单位转换。

# -*- coding: UTF-8 -*-
class Meter(object):
    """
    对于单位"米"的描述器
    """
    def __init__(self, value=0.0):
        self.value = float(value)
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        self.value = float(value)
class Foot(object):
    """
    对于单位"英尺"的描述器
    """
    def __get__(self, instance, owner):
        return instance.meter * 3.2808
    def __set__(self, instance, value):
        instance.meter = float(value) / 3.2808
class Distance(object):
    """
    用米和英寸来表示两个描述器之间的距离
    """
    meter = Meter(10)
    foot = Foot()
  使用时:
>>>d = Distance()
>>>print d.foot
>>>print d.meter
32.808
10.0

复制

  有时候,尤其是当你在处理可变对象时,你可能想要复制一个对象,然后对其做出一些改变而不希望影响原来的对象。这就是Python的copy所发挥作用的地方。

__copy__(self):

  定义了当对你的类的实例调用copy.copy()时所产生的行为。copy.copy()返回了你的对象的一个浅拷贝——这意味着,当实例本身是一个新实例时,它的所有数据都被引用了——例如,当一个对象本身被复制了,它的数据仍然是被引用的(因此,对于浅拷贝中数据的更改仍然可能导致数据在原始对象的中的改变)。

__deepcopy__(self, memodict={}):

  定义了当对你的类的实例调用copy.deepcopy()时所产生的行为。copy.deepcopy()返回了你的对象的一个深拷贝——对象和其数据都被拷贝了。memodict是对之前被拷贝的对象的一个缓存——这优化了拷贝过程并且阻止了对递归数据结构拷贝时的无限递归。当你想要进行对一个单独的属性进行深拷贝时,调用copy.deepcopy(),并以memodict为第一个参数。

其他方法

用于比较的魔术方法

__cmp__(self, other)    是比较方法里面最基本的的魔法方法

__eq__(self, other) 定义相等符号的行为,==

__ne__(self,other)  定义不等符号的行为,!=

__lt__(self,other)  定义小于符号的行为,59e80febc0f09b1a1fdbb130e74db23b

__le__(self,other)  定义小于等于符号的行为,7bb385438cfbf344aabb4f1f2d405f04=

数值计算的魔术方法

单目运算符和函数

__pos__(self)   实现一个取正数的操作

__neg__(self)   实现一个取负数的操作

__abs__(self)   实现一个内建的abs()函数的行为

__invert__(self)    实现一个取反操作符(~操作符)的行为

__round__(self, n)  实现一个内建的round()函数的行为

__floor__(self) 实现math.floor()的函数行为

__ceil__(self)  实现math.ceil()的函数行为

__trunc__(self) 实现math.trunc()的函数行为

双目运算符或函数

__add__(self, other)    实现一个加法

__sub__(self, other)    实现一个减法

__mul__(self, other)    实现一个乘法

__floorp__(self, other)   实现一个“//”操作符产生的整除操作()

__p__(self, other)    实现一个“/”操作符代表的除法操作

__truep__(self, other)    实现真实除法

__mod__(self, other)    实现一个“%”操作符代表的取模操作

__pmod__(self, other) 实现一个内建函数pmod()

__pow__ 实现一个指数操作(“**”操作符)的行为

__lshift__(self, other) 实现一个位左移操作(c1aabf317259b36e5bd7dbf11eaac32a>)的功能

__and__(self, other)    实现一个按位进行与操作(&)的行为

__or__(self, other) 实现一个按位进行或操作的行为

__xor__(self, other)    __xor__(self, other)

增量运算

__iadd__(self, other)   加法赋值

__isub__(self, other)   减法赋值

__imul__(self, other)   乘法赋值

__ifloorp__(self, other)  整除赋值,地板除,相当于 //= 运算符

__ip__(self, other)   除法赋值,相当于 /= 运算符

__itruep__(self, other)   真除赋值

__imod_(self, other)    模赋值,相当于 %= 运算符

__ipow__    乘方赋值,相当于 **= 运算符

__ilshift__(self, other)    左移赋值,相当于 10e7b80211ed5d80322db6f717003170>= 运算符

__iand__(self, other)   与赋值,相当于 &= 运算符

__ior__(self, other)    或赋值

__ixor__(self, other)   异或运算符,相当于 ^= 运算符

类型转换

__int__(self)   转换成整型

__long__(self)  转换成长整型

__float__(self) 转换成浮点型

__complex__(self)   转换成 复数型

__oct__(self)   转换成八进制

__hex__(self)   转换成十六进制

__index__(self) 如果你定义了一个可能被用来做切片操作的数值型,你就应该定义__index__

__trunc__(self) 当 math.trunc(self) 使用时被调用__trunc__返回自身类型的整型截取

__coerce__(self, other) 执行混合类型的运算

The above is the detailed content of Introducing the use of magic methods in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn