Python Object-oriented---private properties and private methods

Source: Internet
Author: User

01, application scenario and definition mode application scenario
    • In real-world development, some properties or methods of an object may only want to be used inside an object and not be externally accessible to
    • A private property is a property that an object does not want to expose
    • Private Methods are methods that objects do not want to expose
How to define
    • when defining a property or method , add an underscore before the property name or method name , defined as a private property or method

    class Women:        def __init__(self, name):            self.name = name            self.__age = 18            # def __secret(self):        def secret(self):            # 在对象的方法内部,是可以访问对象的私有属性的            print("%s 的年龄是 %d" % (self.name, self.__age))            namei = Women("娜美")    # 私有属性和私有方法,在外界不能直接别访问    # namei.__age()    # namei.__secret()    namei.secret()        #  结果呈现    娜美 的年龄是 18
02, pseudo-private properties and private methods

tip : In daily development, do not use this method to access the object's private properties or private methods

pythonIn, and there is no real sense of private

    • In the name of the property, the method is actually a number of special processing, so that the outside world can not access the
    • How to handle : Add the name in front of __类名__类名__名称
    class Women():        def __init__(self, name):            self.name = name            self.__age = 18            def __secret(self):        # def secret(self):            # 在对象的方法内部,是可以访问对象的私有属性的            print("%s 的年龄是 %d" % (self.name, self.__age))            namei = Women("娜美")    # 私有属性和私有方法,在外界不能直接别访问    # namei.__age()    namei._Women__secret()    # namei.secret()        # 结果呈现    娜美 的年龄是 18

Python Object-oriented---private properties and private methods

Related Article

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.