Object-oriented methods and properties

basic method

__new__(cls[, ...])

1. __new__ is the first method called when an object is instantiated
2. Its first parameter is the class, and other parameters are used to pass directly to the __init__ method
3. __new__ decides whether to use the __init__ method because __new__ can call other classes

The constructor or directly return another instance object as an instance of this class, if __new__

No instance object is returned, __init__ will not be called

4. __new__ is mainly used to inherit an immutable type such as a tuple or string

__init__(self[, ...])

Constructor, the initialization method called when an instance is created,

Mainly used to set properties for instances

__del__(self)

Destructor, a method called when an instance is destroyed

__call__(self[, args...])

The method to execute when the instance is called

__len __ (self)

Defines the behavior when called by len()

__repr__(self)

Defines the behavior when called by repr()

__str__(self)

Defines the behavior when called by str(), if a class does not define __str__ and defines __repr__, str() will execute __repr__

__bytes__(self)

Defines the behavior when called by bytes()

__hash__(self)

Defines the behavior when called by hash()

__bool__(self)

Defines the behavior when called by bool(), which should return True or False. True and False are determined by len() in some python objects.

__format__(self, format_spec)

Defines the behavior when format() is called

Magic methods related to properties

__getattr__(self, name)

Defines the behavior when the user tries to get a property that does not exist

__getattribute__(self, name)

Defines the behavior when properties of this class are accessed

__setattr__(self, name, value)

Defines the behavior when a property is set

When you define this method, be sure to pay attention to the assignment of attributes in __init__()

example:

class Local(object):

    def __init__(self):
        # If directly self.storage = {}, there will be a loop call
        object.__setattr__(self,'storage',{})

    def __setattr__(self, k, v):
        ident = get_ident()
        if ident in self.storage:
            self.storage[ident][k] = v
        else:
            self.storage[ident] = {k: v}

    def __getattr__(self, k):
        ident = get_ident()
        return self.storage[ident][k]     

__delattr__(self, name)

Defines the behavior when an attribute is deleted

__dir __ (self)

Defines the behavior when dir() is called, this method returns all properties and method names of the class or object

class aa:
    a = 1
    b = 2
    def c(self):
        pass

d = dir (aa)
c = aa()
ce = 11
f = dir(c)
print(set(d)^set(f)) # {'e'}
print(d)
print(f)

__get__(self, instance, owner)

If a class defines it, the class can be called a descriptor. The owner is the owner's class, and the instance is the instance that accesses the descriptor. If the access is not through the instance, but through the class, the instance is None. (The instance of descriptor accessing itself will not trigger __get__, but will trigger __call__, which only makes sense when descriptor is an attribute of other classes.)

example:

class C(object):
    a = 'abc'

    def __getattribute__(self, *args, **kwargs):
        print("__getattribute__() is called")
        return object.__getattribute__(self, *args, **kwargs)

    #    return "haha"
    def __getattr__(self, name):
        print("__getattr__() is called ")
        return name + " from getattr"

    def __get__(self, instance, owner):
        print("__get__() is called", instance, owner)
        return self

    def foo(self, x):
        print(x)


class C2(object):
    d = C()
if __name__ == '__main__':
    c = C()
    c2 = C2()
    c.a # __getattribute__() is called
    c2.d  # __get__() is called <__main__.C2 object at 0x000001BA4EBFBB00> <class '__main__.C2'>

__set__(self, instance, value)

Defines the behavior when the descriptor's value is changed

__delete__(self, instance)

Defines the behavior when the descriptor's value is deleted

uncommonly used

comparison operator

__lt__(self, other) Defines the behavior of the less-than sign: x < y calls x.__lt__(y)
__le__(self, other) Define the behavior of the less-than-equal sign: x <= y call x.__le__(y)
__eq__(self, other) Defines the behavior of the equal sign: x == y calls x.__eq__(y)
__ne__(self, other) Defining the behavior of the inequality sign: x != y calls x.__ne__(y)
__gt__(self, other) Defines the behavior of the greater-than sign: x > y calls x.__gt__(y)
__ge__(self, other) Define the behavior of the greater-than-equal sign: x >= y call x.__ge__(y)

arithmetic operators

_add__(self, other) Define the behavior of addition: +
__sub__(self, other) Define the behavior of subtraction:-
__mul__(self, other) Define the behavior of multiplication: *
__truediv__(self, other) Define the behavior of true division :/
__floordiv__(self, other) Defines the behavior of integer division: //
__mod__(self, other) Define the behavior of the modulo algorithm: %
__divmod__(self, other) Defines the behavior when called by divmod()
__pow__(self, other[, modulo]) Defines the behavior when called by power() or ** evaluated
__lshift__(self, other) Defines the behavior of bitwise left shift: <<
__rshift__(self, other) Defines the behavior of bitwise right shift: >>
__and__(self, other) Defines the behavior of the bitwise AND operation: &
__xor__(self, other) Defines the behavior of the bitwise XOR operation: ^
__or__(self, other) Define the behavior of the bitwise OR operation: |

Inverse operation

__radd__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rsub__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rmul__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rtruediv__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rfloordiv__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rmod__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rdivmod__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rpow__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rlshift__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rrshift__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rxor__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__ror__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)

Increment assignment operator

__iadd__(self, other) Defines the behavior of assignment addition: +=
__isub__(self, other) Defines the behavior of assignment subtraction: -=
__imul__(self, other) Defines the behavior of assignment multiplication: *=
__itruediv__(self, other) Defines the behavior of assignment true division: /=
__ifloordiv__(self, other) Defines the behavior of assignment integer division: //=
__imod__(self, other) Defines the behavior of the assignment modulo algorithm: %=
__ipow__(self, other[, modulo]) Defines the behavior of assignment exponentiation: **=
__ilshift__(self, other) Defines the behavior of an assignment bitwise left shift: <<=
__irshift__(self, other) Defines the behavior of an assignment bitwise right shift: >>=
__iand__(self, other) Defines the behavior of the bitwise AND operation of assignment: &=
__ixor__(self, other) 定义赋值按位异或操作的行为:^=
__ior__(self, other) 定义赋值按位或操作的行为:|=

一元操作符

__neg__(self) 定义正号的行为:+x
__pos__(self) 定义负号的行为:-x
__abs__(self) 定义当被 abs() 调用时的行为
__invert__(self) 定义按位求反的行为:~x

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325135241&siteId=291194637