您的位置:首页 > 编程语言 > Python开发

python 属性私有化问题 @property简化私有属性的访问方式

2019-06-27 15:40 399 查看
版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

1,xx

一般情况下使用的变量

2,_xx 单下划线

在某人模块中,如果变量是 _xx 形式的
import 模块名 变量可正常使用
但是 from 模块名 import * 的方式,变量无法使用

3,__xx 双下划线

类的私有属性/类的私有方法 只能在类的内部访问
不能在类的外部直接访问,但是可以间接访问
python解释器会对私有属性和私有方法进行 名字重整(改名)
重整原则为:_类名__私有属性名或私有方法名

class Person:
def __init__(self, name, age):
self.name = name
self.__age = age

def show_info(self):
print("{}为年龄为{}".format(self.name, self.__age))

def __test(self):
print("我是类的私有方法")
p = Person("皮皮", 18)
p.show_info()
print(dir(p))
print(p._Person__age)
p._Person__test()

运行结果为:

皮皮为年龄为18
['_Person__age', '_Person__test', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'show_info']
18
我是类的私有方法

4,__xx__主要用于方法

例如初始化方法,str方法,del方法,new方法
这些方法不需要自己调用 例如创建对象的时候,会自动先执行new方法,再执行初始化方法

注意:
自定义方法要避免与这些内置的方法重名

5,xx_ 主要用来区分变量名或者方法名

一般情况下不常用

6,使用property简化私有属性的访问方式

class Person:
def __init__(self, name, age):
self.name = name
self.__age = age

def get_age(self):
return self.__age

def set_age(self, age):
if isinstance(age, int):
self.__age = age
else:
raise TypeError("类型错误")

p = Person("皮皮", 18)
p.set_age(16)
print(p.get_age())

运行结果为

16

另外一种方式为:

class Person:
def __init__(self, name, age):
self.name = name
self.__age = age

def get_age(self):
return self.__age

def set_age(self, age):
if isinstance(age, int):
self.__age = age
else:
raise TypeError("类型错误")

age = property(get_age, set_age)			# property关联两个方法

p = Person("皮皮", 18)
print(p.age)
p.age = 20
print(p.age)

运行结果为:

18
20

7,使用@property简化私有属性的访问方式

使用@property装饰器 取代get和set方法

class Account:
def __init__(self):
self._money = 0

@property           # @property 固定写法
def money(self):
return self._money

@money.setter       # @属性.setter 固定写法
def money(self, money):
if isinstance(money, int):
self._money = money
else:
raise TypeError("类型错误")

m = Account()
m.money = 100print(m.money)

运行结果为:

100
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: