What is __slots__? Pros, cons.
Classes store fields and their values in a secret dictionary dict . Since the dictionary is a mutable structure, you can add and remove fields from the class on the fly. The slots parameter in the class hard-fixes the set of class fields. Slots are used when a class can have a lot of fields, such as in some ORMs, or when performance is critical because slot access is faster than dictionary lookups.
Slots are actively used in the requests and falcon libraries.
Disadvantages: you cannot assign a field to a class that is not in the slots. Methods __getattr__ and __setattr__ do not work.
What is the meaning of _value, __value parameters
A class field with a single leading underscore indicates that the parameter is only used within the class. At the same time, it is available for external access.
class foo ( object ):
def __init__ ( self ):
self ._bar = 42
Foo()._bar
>>> 42
Modern IDEs like PyCharm will highlight field access with an underscore, but there will be no runtime error.
Double underscore fields are available inside the class, but are not available from outside. This is achieved by a tricky trick: the interpreter assigns names like ___ to such fields. Knowing this rule, you can get the value of a hidden field outside the class, but it looks very ugly.
class foo ( object ):
def __init__ ( self ):
self .__bar = 42
Foo().__bar
>>> AttributeError : 'Foo' object has no attribute '__bar'
Foo()._Foo__bar
>>> 42
Multithreading
How is multithreading implemented in python? What modules?
Multithreading is achieved by the Threading module. These are native Posix threads. Such threads are executed by the operating system, not by the virtual machine.
What is GIL? How does it work? What kind problems ?
Global Interpreter Lock. A feature of the interpreter when only one thread can be executed at a time. All this time, the rest of the threads are idle. GIL is not only in Python, but also in other scripting languages, such as Ruby.
The reason for the existence of the GIL is that there has not yet been a safe way for these interpreters to negotiate data changes. For example, if one thread removes all elements from a list, and the second one starts iterating over it, an error is guaranteed to occur.
The GIL works like this: a certain time slice is allocated for each thread. It is measured in machine units “ticks” and is 100 by default. As soon as 100 ticks have been spent on a thread, the interpreter abandons this thread and switches to the second one, spends 100 ticks on it, then the third, and so on in a circle. This algorithm guarantees that all threads will be allocated equal resources.
The problem is that due to the GIL, not all tasks can be solved in threads. On the contrary, their use most often reduces the performance of the program. Using threads, you need to monitor access to shared resources: dictionaries, files, database connections.
Do'stlaringiz bilan baham: |