In Python, you can define a property as a private property by adding a double underscore in front of the property variable name, such as an example:
Copy Code code as follows:
#! Encoding=utf-8
Class A:
def __init__ (self):
# define private properties
Self.__name = "Wangwu"
# normal attribute definition
Self.age = 19
A = A ()
# Normal output
Print A.age
# hint cannot find the attribute
Print A.__name
To perform the output:
Copy Code code as follows:
Traceback (most recent call last):
File "C:\Users\lee\Documents\Aptana Studio 3 workspace\testa\a.py", line <module>
Print A.__name
ATTRIBUTEERROR:A instance has no attribute ' __name '
When you access a private property __name, you are prompted not to find the property members, not to prompt permission, and so on, so when you write without an error:
Copy Code code as follows:
#! Encoding=utf-8
Class A:
def __init__ (self):
# define private properties
Self.__name = "Wangwu"
# normal attribute definition
Self.age = 19
A = A ()
A.__name = "Lisi"
Print A.__name
Execution results:
1
Lisi
Even inheritance in Python cannot access private variables, such as:
Copy Code code as follows:
#! Encoding=utf-8
Class A:
def __init__ (self):
# define private properties
Self.__name = "Wangwu"
# normal attribute definition
Self.age = 19
Class B (A):
def sayname (self):
Print Self.__name
b = B ()
B.sayname ()
Execution results:
Copy Code code as follows:
Traceback (most recent call last):
File "C:\Users\lee\Documents\Aptana Studio 3 workspace\testa\a.py", line <module>
B.sayname ()
File "C:\Users\lee\Documents\Aptana Studio 3 workspace\testa\a.py", line, in Sayname
Print Self.__name
ATTRIBUTEERROR:B instance has no attribute ' _b__name '
Or the parent class can access the private properties of the subclass, such as:
Copy Code code as follows:
#! 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:
Copy Code code as follows:
Wangwu
Traceback (most recent call last):
File "C:\Users\lee\Documents\Aptana Studio 3 workspace\testa\a.py", line, in <module>
B.say ()
File "C:\Users\lee\Documents\Aptana Studio 3 workspace\testa\a.py", line 6, in say
Print Self.__age
ATTRIBUTEERROR:B instance has no attribute ' _a__age '