The object-oriented design of python is different from that of C ++. Note the following:
-
- Python classes do not have access permissions, that is, all variables are accessible.
In fact, Python has a private mechanism, that is, adding __before the attribute, but this private mechanism is actually pseudo-private, because it actually uses an alias to store this attribute.
For example, in class A, self. _ A = 4. In fact, _ A is changed to _ A and kept in class.
- There is no static statement. Classes and instances are differentiated. An attribute or method can belong to a class or an instance.
See the following example.
Class A:
I = ' Class VaR '
Def _ Init __ (Self ):
Self. I = ' Instance VaR '
A = ()
Print . i,. I
# result class var instance var
class the elements and functions between instances are independent.
of course, if you want to define a method of the class, because the Forced method of the old object definition must contain the self parameter, otherwise the call will fail, so the static function is required, you can do this:
class :
I = ' class var '
def __ init __< /span> (Self):
self. I = ' instance var '
def F (): pass
F = staticmethod (f)
- The attributes and methods of classes and instances are actually placed in the dictionary of classes and instances, that is, _ dict _. Therefore, they can be seen as two different things.
The class itself is also an object, so both the class and instance canProgramTo add, modify, and delete a file. You can even use del to delete attributes and functions in the class.
-
- So how does Python find the attributes and methods in a class or instance?
All classes and instances in Python form an object property tree based on their inheritance relationships.
The leaf node of the tree is an instance, and the internal node is determined by the inheritance relationship between classes.
When. A searches for an element in a node in this tree. If the current node does not have this element, it searches up until the root node, if there are more than two paths in the process (think about why), go up from the left, if not found at the root node, return to the point where the split occurs, and then forward to the right.
This method does not have to worry about the situation in C ++ even if multiple inheritance occurs (actually two or more paths mentioned above.I found that most of the interviews are based on what I said at, so it is very important to understand .. And I think this method is quite elegant ~~