Built-in functions in python (double underscore)

1. The role of __name__ = '__main__' in python

If we are directly executing a .py file, then "__name__ == '__main__'" in the file is True, but if we import the file from another .py file through import, then __name__ The value is the name of our py file instead of __main__.

This function is also useful: when debugging code, add some of our debugging code to "if __name__ == '__main__'", we can make external modules call without executing our debugging code, but if we want to troubleshoot When there is a problem, directly execute the module file, and the debugging code can run normally!

2. Other commonly used

x.__contains__(y) is equivalent to y in x. There are functions
__base__, __bases__, __mro__ in containers such as list, str, dict, set, etc., about class inheritance and function search paths.
class.__subclasses__(), returns a list of subclasses
x.__call__(...) == x(...)
x.__cmp__(y) == cmp(x,y)
x.__getattribute__('name') == x.name == getattr(x, 'name'), call
x.__hash__() == hash(x)
x.__sizeof__(), x is the number of bytes in memory, x is class If so, it should be x.__basicsize__
x.__delattr__('name') == del x.name
__dictoffset__ attribute tells you the offset to where you find the pointer to the __dict__ object in any instance object that has one. It is in bytes.
__flags__, returns a string of numbers to determine whether the type can be serialized (if it's a heap type), __flags__ & 512
S.__format__, useful for some classes
x.__getitem__(y) == x[y], correspondingly there is __setitem__, some unmodifiable types such as set, str does not have __setitem__
x.__getslice__(i, j) == x[i:j], there is a Doubt, x='123456789', x[::2], how to implement
__subclasscheck__(), check if a class is subclass
__instancecheck__(), check if an object is an instance
__itemsize__, These fields allow calculating the size in bytes of instances of the type. 0 is variable length, non-0 is fixed length
x.__mod__(y) == x%y, x.__rmod__(y) == y%x
x.__module__ , x belongs to module
x. __mul__(y) == x*y, x.__rmul__(y) == y*x

__reduce__, __reduce_ex__ , for pickle

After __slots__ is used, the class becomes static. Without __dict__, the instance cannot add new attributes.

__getattr__ This function is called after the general lookup attribute is not found

__setattr__ replaces the general assignment operation. If there is this function, this function will be called. If you want to call the normal assignment method, use object.__setattr__(self, name, value)

__delattr__ is the same as __setattr__, called when del obj.name is meaningful

 

Reference documentation:

1.python: Analysis of the role of __name__ = '__main__' in python: https://www.cnblogs.com/alan-babyblog/p/5147770.html

2. Those functions and variables starting with double underscores in python -- reprint: https://www.cnblogs.com/nkwy2012/p/6264031.html

 

Guess you like

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