首页 > 技术文章 > Python——私有化 和 属性property

yxh-amysear 2018-08-11 18:38 原文

Python——私有化 和 属性property

一、私有化

  • xx: 公有变量
  • _x: 单前置下划线,私有化属性或方法,from somemodule import *禁止导入,类对象和子类可以访问
  • __xx:双前置下划线,避免与子类中的属性命名冲突,无法在外部直接访问(名字重整所以访问不到)
  • __xx__:双前后下划线,用户名字空间的魔法对象或属性。例如:__init__ , __ 不要自己发明这样的名字
  • xx_:单后置下划线,用于避免与Python关键词的冲突

通过name mangling(名字重整(目的就是以防子类意外重写基类的方法或者属性)如:_Class__object)机制就可以访问private了。

总结

  • 父类中属性名为__名字的,子类不继承,子类不能访问
  • 如果在子类中向__名字赋值,那么会在子类中定义的一个与父类相同名字的属性
  • _名的变量、函数、类在使用from xxx import *时都不会被导入

 

二、属性property

1. 私有属性添加getter和setter方法

 1 class Money(object):
 2     def __init__(self):
 3         self.__money = 0
 4 
 5     def getMoney(self):
 6         return self.__money
 7 
 8     def setMoney(self, value):
 9         if isinstance(value, int):
10             self.__money = value
11         else:
12             print("error:不是整型数字")

2. 使用property升级getter和setter方法

 1 class Money(object):
 2     def __init__(self):
 3         self.__money = 0
 4 
 5     def getMoney(self):
 6         return self.__money
 7 
 8     def setMoney(self, value):
 9         if isinstance(value, int):
10             self.__money = value
11         else:
12             print("error:不是整型数字")
13     money = property(getMoney, setMoney)

运行结果:

In [1]: from get_set import Money

In [2]: 

In [2]: a = Money()

In [3]: 

In [3]: a.money
Out[3]: 0

In [4]: a.money = 100

In [5]: a.money
Out[5]: 100

In [6]: a.getMoney()
Out[6]: 100

3. 使用property取代getter和setter方法

@property成为属性函数,可以对属性赋值时做必要的检查,并保证代码的清晰短小,主要有2个作用

  • 将方法转换为只读
  • 重新实现一个属性的设置和读取方法,可做边界判定
 1 class Money(object):
 2     def __init__(self):
 3         self.__money = 0
 4 
 5     @property
 6     def money(self):
 7         return self.__money
 8 
 9     @money.setter
10     def money(self, value):
11         if isinstance(value, int):
12             self.__money = value
13         else:
14             print("error:不是整型数字")

运行结果:

In [3]: a = Money()

In [4]: 

In [4]: 

In [4]: a.money
Out[4]: 0

In [5]: a.money = 100

In [6]: a.money
Out[6]: 100

 

推荐阅读