Python defines instance methods

Source: Internet
Author: User

defining instance methods the private property of an instance is a property that begins with __ and cannot be accessed externally, what is the use of these attribute definitions? Although private properties cannot be accessed externally, they can be accessed from within the class. In addition to defining the properties of an instance, you can define the methods of the instance. An instance is a function defined in a class whose first argument is always self, pointing to the instance itself that invokes the method, and the other arguments are exactly the same as a normal function:classPerson (object):def __init__(self, name): Self.__name=namedefget_name (self):returnSelf.__nameget_name (self) is an instance method whose first argument is self. __init__(self, name) can actually be seen as a special instance method. The invocation instance method must be called on the instance: P1= Person ('Bob')PrintP1.get_name ()#Self does not require explicit pass- through#= Bobwithin an instance method, all instance properties can be accessed, so that if the external needs access to private properties, which can be obtained through a method call, the form of the data encapsulation can simplify the external invocation in addition to protecting internal data consistency. Task please add a private property to the person class__score, representing fractions, and then adding an instance method Get_grade (), which can be based on__scoreThe values are returned A-Excellent, B-pass, C-fail three.

Python defines instance methods

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.