How python interpreter is work?

How python interpreter is work?
Whether writing program in which frameworks, will spend a lot of time to implement those methods will be called the framework itself, Python is no exception. When confronted with special syntax, Python interpreter will use a special method to activate some basic object manipulation, special methods of these names begin with two underscore to two trailing underscore
such obj [key] is behind getitem method,

import collections
from random import choice
import pysnooper


Card = collections.namedtuple('Card', ['rank', 'suit'])


class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA')
    suits = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]

    @pysnooper.snoop()
    def __len__(self):
        return len(self._cards)

    @pysnooper.snoop()
    def __getitem__(self, position):
        return self._cards[position]

    @pysnooper.snoop()
    def __contains__(self, item):
        if item:
            return True


if __name__ == '__main__':
    deck = FrenchDeck()
    print(len(deck))
    print(deck[1])

First clear that there is a special method is to be called the Python interpreter, you do not need to call them. That does not my_object. Len () such an approach, but should use len (my_object). In performing len (my_object), if my_object is an object-defined classes, then Python will call one of their own to achieve by you len method. However, if the built-in Python type, such as a list (List), the string (STR), a sequence of bytes (ByteArray) and the like, it will copy a shortcut CPython, len actually directly back in the ob_size PyVarObject properties. PyVarObject is a C language structure of the memory built-in variable-length object. This value is directly read much faster than calling a method.

In many cases, calling a special method is implicit, such as for i in x: This statement, in fact, behind using a iter (x), and this function is behind the X-. Iter () method. Of course, the premise is that this method is implemented in x.

Usually you do not need to code directly using a special method. Unless there is a large number of meta-programming, direct call a special method of frequency should be much lower than the number of times you go to achieve them. The only exception may be the init method, your code may often use it aimed at your own subclass init call the superclass constructor method.

Here are some special way in the realization of
repr , ABS , the Add and mul

from math import hypot
import pysnooper


class Vector:

    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    @pysnooper.snoop()
    def __repr__(self):
        return 'Vector(%r, %r)' % (self.x, self.y)

    @pysnooper.snoop()
    def __str__(self):
        return '对象字符串化%r' % self

    @pysnooper.snoop()
    def __abs__(self):
        return hypot(self.x, self.y)

    @pysnooper.snoop()
    def __bool__(self):
        return bool(abs(self))

    @pysnooper.snoop()
    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Vector(x, y)

    @pysnooper.snoop()
    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)

    @pysnooper.snoop()
    def __len__(self):
        return True if self else False


if __name__ == "__main__":
    vector = Vector(3, 4)
    vector_1 = Vector(5, 12)
    print(vector.__repr__())
    print(abs(vector))
    vector_3 = vector + vector_1
    print(vector_3)
    print(vector_3*3)
    print(str(vector_3))
    print(vector_3.__len__())
    print(bool(vector_3))
    bool()

repr and STR (both print output effect) the difference that the latter is () function is used in str, or the printing of an object when using the print function and are called, and it returns a string to the end user more friendly.
If you want to implement one of the two special methods, repr is a better choice, because if an object is not str function, which in turn requires Python to call it, the interpreter will use repr instead.

Other special python methods
Here Insert Picture Description
Here Insert Picture Description
here to make a special note for __len__: For user-defined method, Python will call themselves by the __ len__ which method you achieve, but for python built-in type, such as a list (list), string (STR), a sequence of bytes (ByteArray) and the like, it will copy a shortcut CPython, len actually directly back in the ob_size PyVarObject properties. PyVarObject is a C language structure of the memory built-in variable-length object. This value is directly read much faster than calling a method.

Guess you like

Origin blog.csdn.net/MZP_man/article/details/92248872