python higher order: magic function

Keywords: Python Back-end

Summary:
Dynamic Language: Python is a dynamic language, with the duck model at the bottom: when you see a bird walking like a duck, swimming like a duck, and calling like a duck, it can be called a duck.

In the duck type, the focus is not on the type of object itself, but on how it is used. In programming, duck typing is a style of dynamic type. In this style, the valid semantics of an object are determined not by inheriting from a particular class or implementing a specific interface, but by a collection of current methods and properties.

The specific implementation is to use magic functions to achieve a variety of additional functions or attributes. Customization is not supported; you can only use the written version that comes with Python.

It can be divided into: 1. Non-mathematical operations; 2. Mathematical operations.

1. Non-mathematical operations:

  1.1 The string represents:__repr__,__str__

  1.2 Collection sequence correlation:__len__,__getitem__,__setitem__,__delitem__,__contains__

  1.3 Iterative correlation:__iter__,__next__

  1.4 Callable:__call__

  1.5with Context Manager:__enter__,__exit__

  1.6 Numeric conversion:__abs__,__bool__,__int__,__float__,__hash__,__index__

  1.7 Metaclass correlation:__new__,__init__

  1.8 Attribute correlation:__getattr__, __setattr__,__getattribute__,setattribute__,__dir__

  1.9 Attribute descriptors:__get__,__set__, __delete__

  1.10 Program:__await__,__aiter__,__anext__,__aenter__,__aexit__

2. Mathematical operations:

  2.1 Unary operator:__neg__(-),__pos__(+),__abs__

   2.2 Binary operators:__lt__(<), __le__ <= , __eq__ == , __ne__ != , __gt__ > , __ge__ >=

  2.3 Arithmetic operators:__add__ + , __sub__ - , __mul__ * , __truediv__ / , __floordiv__ // ,u mod_%, u Divmod_u Divmod(), u Pow_ ** Or pow(), u Round_u Round()

  2.4 Reverse Arithmetic Operator:__radd__ , __rsub__ , __rmul__ , __rtruediv__ , __rfloordiv__ , __rmod__ ,__rdivmod__ , __rpow__

  2.5 Incremental assignment arithmetic operator:__iadd__ , __isub__ , __imul__ , __itruediv__ , __ifloordiv__ , __imod__ ,__ipow__

  2.6 Bit operators:__invert__ ~ , __lshift__ << , __rshift__ >> , __and__ & , __or__ | , __xor__ ^

  2.7 Reverse Bit Operator:__rlshift__ , __rrshift__ , __rand__ , __rxor__ , __ror__

  2.8 Incremental assignment bitwise operator:__ilshift__ , __irshift__ , __iand__ , __ixor__ , __ior__

Specific source code parsing: Essentially, the for loop is an iterator, and the class itself does not have an iterator. If an iterator is not available, it will try to get related methods, such as iter, getitem, etc. until there is no corresponding function or method that can be iterated, an exception will be thrown. Essentially, getitems give classes iteratively traversable functionality, and the interpreter does it for us without special intervention.

class Person(object):
    def __init__(self, boys):
        self.p_boys = boys

    def __len__(self):
        return len(self.p_boys)

    def __getitem__(self, item):
    # Magic functions themselves are not methods of classes, and any class can be added. Magic functions are not linked to exclusive classes, but only to enhance the properties or methods of classes. Increase to an iterative type.
        return self.p_boys[item]

if __name__ =='__main__':

    boys = ['hzb1','hzb2','hzb3']

    p1 = Person(boys)

    p1_boys = p1.p_boys

    # Visit class objects directly to find traversal. Without adding: TypeError:'Person'object is not Iterable

    for one in p1:
        print(one)
        print(p1[1])   # Support slicing  # The underlying principle is u getitem_u This magic function works.
        print(len(p1))# Supports statistical length

The magic function itself does not use much, it is only the concept of data model, it does not belong to inheritance, it does not belong to this kind of object, it can be considered as an independent existence, and it enriches this type after adding. Understanding the use of magic functions and data models is important for understanding Python design concepts, somewhat like interfaces in Java.

Another example is:

class Cat(object):
    """String formatting."""

    def __init__(self, color):
        self.name ="Kitty"
        self.color = color

    def __str__(self):
        return ",".join(self.color)

    def __repr__(self):
        return ",".join(self.color)

    if __name__ =='__main__':
        c1 = Cat(['red','green','blue'])
        print(c1)   # => C1 would have printed only the memory address. red,green,blue

WeChat Public Number: Play Test Development
Welcome to your attention and progress together, thank you!

Posted by OopyBoo on Wed, 24 Nov 2021 09:28:29 -0800