A function defined in a class is only a little different than a normal function, that is, the first argument is always an instance variable, self and when called, it is not passed. In addition, there is no difference between a class method and a normal function, so you can still use default parameters, variable arguments, keyword arguments, and named keyword parameters.
Unlike static languages, Python allows you to bind any data to an instance variable, which means that for two instance variables, although they are different instances of the same class, the variable names you have may be different:
If you want the internal properties to be inaccessible externally, you can add the name of the property with two underscores __ , and in Python, the variable name of the instance __ becomes a private variable (private), which can only be accessed internally and cannot be accessed externally, so We changed the Student class:
After the change, for external code, there is no change, but it has been unable to access from outside 实例变量.__name and 实例变量.__score :
This ensures that external code cannot arbitrarily modify the state inside the object, so that the code is more robust through access-restricted protection.
But what if external code gets name and score? You can add to the student class get_name and get_score this method:
What if I want to allow external code to modify score? You can add additional methods to the student class set_score :
python--Object-oriented