标签:重写 自己 code 总结 mod sel property name 定义
Python——私有化 和 属性property
一、私有化
__init__
, __ 不要自己发明这样的名字通过name mangling(名字重整(目的就是以防子类意外重写基类的方法或者属性)如:_Class__object)机制就可以访问private了。
__名字
的,子类不继承,子类不能访问__名字
赋值,那么会在子类中定义的一个与父类相同名字的属性_名
的变量、函数、类在使用from xxx import *
时都不会被导入
二、属性property
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:不是整型数字")
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
@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
标签:重写 自己 code 总结 mod sel property name 定义
原文地址:https://www.cnblogs.com/yxh-amysear/p/9460657.html