python--Object-oriented

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.