Python-Private properties (variants of double downline)

Source: Internet
Author: User

__x will automatically deform to _ class name __x normal condition
class A:    def foo(self):        print(‘from A‘)    def test(self):        self.foo()class B(A):    def foo(self):        print(‘from B‘)b = B()b.test()# from B
To define Foo as a private
class A:    def __foo(self):    #双下线私有属性在定义时就变形为_A__fa        print(‘from A‘)    def test(self):        self.__foo()    #调用变形后的私有属性对象,即_A__faclass B(A):    def __foo(self):        print(‘from B‘)b = B()b.test()# from A

Principle: The __x private property of the parent class has been transformed to the parent class __x when defined, and the subclass can inherit this property, but cannot overwrite it. So the self of Self.__foo in test () is already bound to the parent class, and __foo () of the subclass cannot be overwritten.

class A:    def __foo(self):    #双下线私有属性在定义时就变形为_A__fa        print(‘from A‘)    def test(self):        self.__foo()    #调用变形后的私有属性对象,即_A__faclass B(A):    def __foo(self):        print(‘from B‘)b = B()b._A__foo()# from A
Disadvantages of Python's private properties

This distortion does not really restrict directly accessing properties from the outside

class A:    def __foo(self):        print(‘from A‘)    def test(self):        self.__foo()a = A()a._A__foo()

Python-Private properties (variants of double downline)

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.