analysis
- Use double-layer loop list derivation
- Use
sum(iterable,start=0), Be carefulsumThe function takes a default parameter , The default is 0- Use
numpyMediumflatten()function- Use
itertoolsMediumchain

analysis
- Use it directly
b' character string ' In the form of- Use
character string .encode()Methodbytes(str,encoding="utf-8")

any
- Prototype
any(iterable,/), The function of underline : The parameters before declaring this function can only be positional parameters- effect return
TrueIfbool(elem)byTrue, For arbitraryiterableInsideelemCome on- If it is
iterableIt's empty. , Then return toFalse

all(iterable,/)
- return
True, IfiterableEverything in itelemOfbool(elem)All back toTrueWhen , The result isTrue- similar
andThe role ofBe careful :IfiterableIt's empty , beallThe return value ofTrue


What is? Python The introspection mechanism of
pythonAt run time, you can get the types and properties of objectspythonIs a strongly typed dynamic language , Strong type means python Implicit type conversions are rarely used , Dynamic language meanspythonIt is allowed to change the type of object at runtime
dir()

Translate :
dir([object])-> String list- Call... Without parameters , Returns the name in the current scope
- If there are parameters , This parameter must be an object . What is returned is the property of the object , In alphabetical order
- If the object overrides
__dir__()Method , The overridden , No, call the defaultdir()Method- For module objects , Returns the properties of the module
- For class objects , Returns the properties of the class , And the properties of the parent class
- For any other object , Return object properties , Class attributes and base class attributes

__dict__
- If it is an instance object, call , Returns the properties in the instance object ( Method does not return ), Properties in the parent class are not returned
- If it is a class object call , The properties and methods of the class object are returned , Similarly, inheritance is not considered

__name__
Not all objects have names , But those objects that have names store their names in their __name__ Properties of the . notes : The name is derived from the object, not from the variable that references it .

The module has a name ,Python The interpreter itself is considered a top-level module or a main module . When running interactively Python When , Local __name__ Variables are assigned values __main__. Same drop , When executed from the command line Python modular , Instead of importing it into another module , Its __name__ Attribute is assigned a value __main__, Instead of the actual name of the module . such , Modules can view their own __name__ Values to determine for themselves how they are being used , As support for another program , Or as the main application executed from the command line . The following idiomatic statements are used in Python Is very common in :
if __name__ == "main":
# do something test
else:
# do nothing
type
type()Function helps us determine what kind of object is , Its return value is the type object :

id( Address / identification )blist and clist Variables refer to the same list object .id() Function returns a unique identifier for any given object .
attribute
Object has properties , also dir() The function returns a list of these properties . But sometimes , We just want to test 1 Whether one or more attributes exist . If the object has the properties we are considering , Then you usually want to retrieve only this attribute . This task can be performed by hasattr() and getattr() Function to complete .

Callable
You can call to represent potential behavior ( Functions and methods ) The object of . It can be used callable() Function to test the callability of an object :
example
stay type() Function provides the type of the object , You can also use isinstance() Function test object , To determine if it is an instance of a particular type or custom class :

Subclass
Questions about classes , There is a concept of inheritance , If there is inheritance, there is the problem of father and son , This is normal in real life , The same is true in becoming a language .
In an inherited relationship , A key concept is attributes , The subclass will inherit the properties of the parent class . So if you decide whether a class is a subclass of another class ?
have access to issubclass() To judge , Pay attention to the judgment here , It is also a subclass of itself .

The following is an example to illustrate the concepts and knowledge used in this article :

Sometimes we meet the need , Need to execute some method of the object , Or assign a value to a field of the object , However, the method name and field name cannot be determined when encoding , You need to pass in a string as a parameter . Take a specific example : When we need to implement a universal DBM When the framework , You may need to assign values to fields of data objects , But we can't predict what fields the data objects using this framework have , In other words , When we write a framework, we need to access unknown properties through some mechanism .
This mechanism is called reflection ( The object itself tells us what properties it has ), Or introspection ( The object itself can know which properties it has ), It is used to obtain object information at run time .
1) Properties of the access object

dir(obj)Call this method to return a return containing
objList of most property names ( There will be some special properties that are not included ).obj The default value of is the current module object .
hasattr(obj,attr):This method is used to check obj Is there one named attr The property of the value of , Returns a Boolean value .
getattr(obj,attr):Calling this method will return obj Middle name is attr The value of the property of value , For example, if attr by
bar, Then return toobj.bar.
setattr(obj,attr,val):Calling this method will give
objThe name isattrThe value attribute of is assigned toval. For example, ifattrbybar, Is equivalent toobj.bar=val.
Access the metadata module of the object (module)
__doc__:docstring . If the module has no documentation , This value is None.__name__:Always the module name at the time of definition , Even if you use import as Nicknamed it , Or assign to another variable name .__dict__:Contains the attribute names available in the module - A dictionary of attributes ; That is, you can use the module name . Object accessed by property name .__file__:Contains the file path of the module . It should be noted that the built-in module does not have this attribute , Accessing it throws an exception .

example (instance)
Instance refers to the object after class instantiation .
__dict__: Contains the available attribute names - Attribute dictionary .__class__: The class object of this instance 
Built in functions and methods (built-in functions and methods)
According to the definition , The built-in (build-in) Module means to use C Write the module , Can pass sys Modular builtin_module_names Field to see which modules are built-in . The functions and methods in these modules can use fewer attributes , However, there is generally no need to view their information in the code .
__doc__: Documentation of functions or methods __name__: The name of a function or method when it is defined __self__: Only methods are available , If it is bound (bound), Then point to the class that calls the method ( If it's a class method ) Or instance ( If it's an example method ), Otherwise None__module__: The module name of the function or method function (function)
This refers specifically to non built-in functions . Be careful , Use... In classes def The definition is method , Although methods and functions have similar behavior , But they are different concepts .
__doc__: Documentation for functions ,__name__: The name of the function when the function is defined __module__: Contains the module name that defines the function , Also note that , It's the module name, not the module object .__dict__: Available properties of function 
First, remember the key memory :
__somename__Start with double underscore , Double underlined member functions .Programmers don't have to call ,Python The interpreter calls itself at the appropriate time or under specific circumstances .My understanding :The magic method is actually such a method , yes Python An embodiment of grammar , A certain fixed syntax will call certain magic methods .
1) __init__(): When creating objects __init__() Will be called automatically , It is used to initialize the instance property according to the passed parameters .
It is itself an initialized function , It's not a constructor .
2) __new__():
- When an object is created, it first calls
__new__()Method to create a class and return an instance of this class .__new__At least one parametercls, Represents the current class , This parameter is instantiated byPythonThe interpreter automatically recognizes__new__There must be a return value , Return the instantiated instance , This is achieved by myself__new__We should pay special attention to it , SurereturnParent class ( adopt super( The name of the class ,cls))__new__Come up with examples , Or directlyobjectOf__new__The examples come out .If __new__ Create an instance of the current class , Automatically called __init__ function , adopt return Statement __new__ The first argument to the function is cls To ensure that it is an instance of the current class , If it's the class name of another class , Then the actual creation returns instances of other classes , In fact, the current class will not be called __init__ function, Also won't whine with other kind of_init__ function

You can see that second one does not call __init__ Method , because __new__ Method does not create an object and returns , therefore __init__() Method objects can be instantiated .

3) __del__ function
Destroy the instantiated object , This is the destructor .
When to call : Automatically triggered when memory is reclaimed , There are two situations in which memory is reclaimed :
- Reclaim all variables after page execution
- All objects are
delWhen
class Bird(object):
def __init__(self, name):
self.name = name
def fly(self):
print("{} Birds are flying !".format(self.name))
def __del__(self):
print("{} The bird is dead , Is deconstructed !".format(self.name))
dark = Bird(" The duck ")
dark.fly()
result :
All objects are del When :

__call__() Method Timing of invocation :
- Automatically triggered when an object is called as a function
- You can simulate functional operations
- It is similar to overloading in a class
()Operator , The instance object can be called like a normal function , WithObject name ()In the form of .
for instance :

If you want a class object , If it can be called as a function, it must be defined __call__ Method , such as :

You can see , By means of Student Class __call__ Method , bring Student The instance object of becomes a callable object .
Python in , Anyone who can () Apply directly to itself and execute , Are called callable objects . Callable objects include custom functions ,Python Built in functions and class instance objects mentioned in this section .
For callable objects , actually name (), It can be understood as name .__call__() Abbreviation . Still take the above example , The last line of code is actually equivalent to :

Then an example of a custom function :

__str__,__repr____str__
- effect : Returns a string object , A string that is primarily user-friendly
- Timing of invocation : 1>
str(obj)2> format() 3> print()
__repr__:
- effect : The official string form used to output an object . The return value must be a string object , It is usually used to show the interpreter .
- Timing of transfer : 1>
repr()Built in function call
Be careful :
If
__repr__Already defined , and__str__Undefined , Then the object calls__str__ = __repr__.

Next, if __str__ When it's undefined , be __repr__ Will be called
