The example demonstrates private properties in Python

  • 2020-04-02 13:58:10
  • OfStack

In Python, you can define a property to be private by placing a double underscore before the name of the property variable. For example:


#! encoding=UTF-8
 
class A:
    def __init__(self):
        
        # Define private properties
        self.__name = "wangwu"
        
        # Common attribute definition
        self.age = 19
        
a = A()
 
# Normal output
print a.age
 
# The property cannot be found
print a.__name

Execution output:

Traceback (most recent call last):
  File "C:UsersleeDocumentsAptana Studio 3 Workspacetestaa.py", line 19, in <module>
    print a.__name
AttributeError: A instance has no attribute '__name'

Accessing private property with s/s, you can't find the property member, not the permission, etc.

#! encoding=UTF-8
 
class A:
    def __init__(self):
        
        # Define private properties
        self.__name = "wangwu"
        
        # Common attribute definition
        self.age = 19
        
 
a = A()
 
a.__name = "lisi"
print a.__name

Execution results:
1
lisi
In Python, even inheritance cannot access private variables to each other, such as:

#! encoding=UTF-8
 
class A:
    def __init__(self):
        
        # Define private properties
        self.__name = "wangwu"
        
        # Common attribute definition
        self.age = 19
        
 
class B(A):
    def sayName(self):
        print self.__name
        
 
b = B()
b.sayName()

Execution results:

Traceback (most recent call last):
  File "C:UsersleeDocumentsAptana Studio 3 Workspacetestaa.py", line 19, in <module>
    b.sayName()
  File "C:UsersleeDocumentsAptana Studio 3 Workspacetestaa.py", line 15, in sayName
    print self.__name
AttributeError: B instance has no attribute '_B__name'

Or a parent class can't access private properties of a subclass, such as:

#! encoding=UTF-8
 
class A:
    def say(self):
        print self.name
        print self.__age
        
 
class B(A):
    def __init__(self):
        self.name = "wangwu"
        self.__age = 20
 
b = B()
b.say()

Execution results:

wangwu
Traceback (most recent call last):
  File "C:UsersleeDocumentsAptana Studio 3 Workspacetestaa.py", line 15, in <module>
    b.say()
  File "C:UsersleeDocumentsAptana Studio 3 Workspacetestaa.py", line 6, in say
    print self.__age
AttributeError: B instance has no attribute '_A__age'


Related articles: