"Privatization" in Python-oriented objects

Source: Internet
Author: User

"Privatization" in Python-oriented objects

Python does not directly support private methods, but relies on the programmer to grasp the timing of the external feature modification.

To make a method or feature private (inaccessible from outside), simply precede its name with a double underline.

__properties that start with a double underscore are "confused" at run time, so direct access is not allowed.

In fact, in Python, properties or methods with double underscores are not private in the true sense, and they can still be accessed.

In the internal definition of a class, all names that begin with a double underscore are "translated" into the form preceded by a single underscore and a class name .

Example:
>>>classTestobj (object): ...__war=" World"...     ...     def __init__(self): ... self.__har="Hello"...         ...     def __foo(self): ...Print(self.)__har+ Self.__war)...         ...     ...>>> T =testobj ()>>> dir (t)#get all the methods inside T['_testobj__foo','_testobj__har','_testobj__war','__class__','__delattr__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']>>> T.__warTraceback (most recent): File"<input>", Line 1,inch<module>T.__warAttributeerror:'Testobj'object has no attribute'__war'>>> T.__harTraceback (most recent): File"<input>", Line 1,inch<module>T.__harAttributeerror:'Testobj'object has no attribute'__har'>>>T.foo () Traceback (most recent): File"<input>", Line 1,inch<module>T.foo () Attributeerror:'Testobj'object has no attribute'Foo'>>>T._testobj__war' World'>>>T._testobj__har'Hello'>>>T._testobj__foo () HelloWorld

"Privatization" in Python-oriented objects

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.