Python private property and method instance analysis _python

Source: Internet
Author: User
Tags in python

This example analyzes the private properties and methods of Python. Share to everyone for your reference. The implementation methods are as follows:

Python's default member functions and member variables are both public and are not decorated with keywords such as public,private in other languages. To define a private variable in Python you only need to add "__" two underscores to the variable name or function name. Internally, Python uses a name mangling technique to replace __membername with _classname__membername, so you'll be prompted to not find it when you use the name of the original private member externally. Like what:

Copy Code code as follows:
Class Person:

def __init__ (self):
Self.__name = ' haha ' #私有属性
Self.age = 22

def __get_name (self): # #私有方法
Return Self.__name

def get_age (self):
Return Self.age

person = person ()
Print Person.get_age ()
Print Person.__get_name ()


The result is: Traceback (most recent call last): File "E:\pythoner\zenghe\jay.py", line, in print person.__get_name () Attrib Uteerror:person instance has no attribute ' __get_name '

The __name we define here are private properties, and __get_name () is a private method. If you visit directly, you will be prompted not to find the relevant properties or methods, but if you really want to access private related data, it is also accessible, strictly speaking, private methods outside their class is accessible, but not easy to handle. Nothing in Python is truly private; internally, the names of private methods and properties are suddenly changed and restored so that they appear unusable with their given names.

I hope this article will help you with your Python programming.

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.