The interview was asked a few times the python oop all hung up, decided to seriously learn it again ~ ~
Python's object-oriented design differs from compiled languages such as C + +, with the following main notes:
- The Python class does not have access to the problem, which means that all variables are accessible.
In fact, Python has a private mechanism, which is to add __ before the attribute, but this private mechanism is actually a pseudo-private, because it is actually using an alias to save this property.
For example, in Class A, self.__a = 4, the __a is actually modified to _a__a persisted in the class.
- There is no static argument that classes and instances are differentiated and that a property or method can belong to a class or to an instance.
Look at the following example
classA:
I= 'class Var'
def __init__(self):
SELF.I= 'instance var'
A=A ()
PrintA.I, A.I
#resultclassvar instance varThe elements and functions between a class and an instance are independent.
Of course, if you want to define a method that belongs to a class, because the old object definition enforcement method is to take the self parameter, otherwise the call will go wrong, so the static function is required to do so:
classA:
I= 'class Var'
def __init__(self):
SELF.I= 'instance var'
deff ():Pass
F=Staticmethod (f)
- The properties and methods in classes and instances are actually placed in a dictionary of classes and instances themselves, which is __dict__, so they can actually be seen as two different things.
The class itself is also an object, so classes and instances can be added, modified, and deleted anywhere in the program. Yes, you can even use Del to delete properties and functions in a class.
- So what does Python look for when you need to use the properties and methods in a class or instance?
All classes and instances in Python will form an object property tree based on their inheritance.
The leaf nodes of the tree are instances, and the internal nodes are determined by the inheritance relationship between the classes.
When you use the A.A method to find an element in a node, it will be searched on this tree, and if the current node does not have the element then continue searching up until the root node, if there are more than two paths in the upward process (think of why this is the case), then go up from the left, if the root node is not found, then return to the point where the fork Go up the right way.
This search method even appears multiple inheritance (in fact, the above-mentioned two path) do not have to worry about the situation in C + +.
About this, I found that most of the interview is still the test of this I 4th said, so actually want to understand is very important. And I think this method is still quite elegant drop ~ ~
Python OOP Summary