__slots__Magic
In Python, each class has an instance property. By default, Python uses a dictionary to hold an instance property of an object. This is useful because it allows us to set any new properties at run time.
However, for small classes with known properties, it can be a bottleneck. This dictionary wastes a lot of memory. Python cannot allocate a fixed amount of memory directly at object creation time to hold all properties. So if you create a lot of objects (I mean thousands of them), it consumes a lot of memory.
But there is still a way to circumvent the problem. This method needs to be used __slots__ to tell Python not to use a dictionary, and to assign space only to a fixed set of properties.
Introspection
Similar to Java reflection.
Introspection (introspection), in the field of computer programming, refers to the ability to judge the type of an object at runtime. It is one of Python's strengths. Everything in Python is an object, and we can investigate those objects carefully. Python contains a number of built-in functions and modules to help us.
DIR/TYPE/ID built-in functions
Inspect module
Container
Collections)
Defaultdict: Advantages over Dict: A single-layer key assignment does not require checking for key presence (need to determine whether a specified key exists before assignment):
fromCollectionsImportdefaultdictcolours= ( ('Yasoob','Yellow'), ('Ali','Blue'), ('Arham','Green'), ('Ali','Black'), ('Yasoob','Red'), ('Ahmed','Silver'),) favourite_colours=defaultdict (list) forName, colourinchColours:favourite_colours[name].append (colour) # There's no need to tell if the name exists, another way to traverse it without distinguishing between the first assignment or the subsequent assignment (these two things are slightly different)Print(favourite_colours)
Nested key avoids keyerror using special methods:
Importlambda= tree () some_dict['colours'[ ' favourite ' " Yellow "
Dequenamedtuple
"Learning Notes" Python advanced features