Python OOP private Mechanism

Source: Internet
Author: User

From this Article At the beginning, I began to share some features of Python Oop, hoping to help you understand Python oop. In fact, Python OOP is different from other languages. Today I will talk about one aspect of private mechanisms.

Other languages, such as Java and C ++, have relatively standardized OOP syntaxes and have public, private, and protected data types. in Python, I can see from my current observations that, Python classes do not have permission control, and all variables can be called externally. You will say: "Python clearly has a private defining method that is to add a Double Slide __in front of a variable or method, but I tell you that this is actually a pseudo-Private python. Only one Program The staff conventions are commonly known as rules. When they are added, they indicate private variables, but you can still call them if you want to call them externally.

Let me give you an example. Code The following is an example:
Class Info (object ):
Def _ init _ (Self ):
Self. _ name = 'Jay'
Def say (Self ):
Print self. _ name


A = Info ()
Print A. _ name

I defined the private property name of an object above. If you use. _ name indicates that the object does not have this attribute, but you can call the value of the private attribute according to my method.

1. You first use print a. _ dict _ to query the set of attributes in object. Expected result: {'_ INFO _ name': 'jar '}
2. Then use print a. _ INFO _ name. You should try to output Jay.

So from the above point of view, python is still very flexible, and its OOP is not truly inaccessible. It is just an agreement for everyone to follow, for example, if you use self to represent the current object in the class, you can also use others, but you are used to self. So it's good to get used to it ..

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.