Home > Backend Development > Python Tutorial > 实例讲解Python中的私有属性

实例讲解Python中的私有属性

WBOY
Release: 2016-06-16 08:42:44
Original
1011 people have browsed it

在Python中可以通过在属性变量名前加上双下划线定义属性为私有属性,如例子:

复制代码 代码如下:

#! encoding=UTF-8
 
class A:
    def __init__(self):
        
        # 定义私有属性
        self.__name = "wangwu"
        
        # 普通属性定义
        self.age = 19
        
a = A()
 
# 正常输出
print a.age
 
# 提示找不到属性
print a.__name

执行输出:
复制代码 代码如下:

Traceback (most recent call last):
  File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 19, in
    print a.__name
AttributeError: A instance has no attribute '__name'

访问私有属性__name时居然提示找不到属性成员而不是提示权限之类的,于是当你这么写却不报错:
复制代码 代码如下:

#! encoding=UTF-8
 
class A:
    def __init__(self):
        
        # 定义私有属性
        self.__name = "wangwu"
        
        # 普通属性定义
        self.age = 19
        
 
a = A()
 
a.__name = "lisi"
print a.__name

执行结果:
1
lisi
在Python中就算继承也不能相互访问私有变量,如:
复制代码 代码如下:

#! encoding=UTF-8
 
class A:
    def __init__(self):
        
        # 定义私有属性
        self.__name = "wangwu"
        
        # 普通属性定义
        self.age = 19
        
 
class B(A):
    def sayName(self):
        print self.__name
        
 
b = B()
b.sayName()

执行结果:
复制代码 代码如下:

Traceback (most recent call last):
  File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 19, in
    b.sayName()
  File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 15, in sayName
    print self.__name
AttributeError: B instance has no attribute '_B__name'

或者父类访问子类的私有属性也不可以,如:
复制代码 代码如下:

#! 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()

执行结果:
复制代码 代码如下:

wangwu
Traceback (most recent call last):
  File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 15, in
    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'
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template