通过过ptoperty方法(类变量读取方法,类变量操作方法)封装数据
class Wife:
def __init__(self,name,age,weight):
self.name = name
#本质:障眼法(实际将变量名改为:__类名__age)
self.set_age(age) #使用方法来修改
#提供公开的读写方法
def get_age(self):
return self.__age
def set_age(self,value):
if 21 <= value <= 31:
self.__age = value
else:
raise ValueError("我不要")
w01 = Wife("aa",86,86)
使用property封装数据
class Wife:
def __init__(self,name,age,weight):
self.name = name
#本质:障眼法(实际将变量名改为:__类名__age)
#使用方法来修改
self.age = age
self.weight = weight
#提供公开的读写方法
def get_age(self):
return self.__age
def set_age(self,value):
if 21 <= value <= 31:
self.__age = value
else:
raise ValueError("我不要")
#属性 property对象拦截对age类变量读写操作
age = property(get_age, set_age)
w01 = Wife("aa",86,86)
w01.age=15#拦截了对类变量age的写操作转到set_age方法
print(w01.age)#拦截了读操作
class Enemy:
def __init__(self,name,hp,attack):
self.name = name
self.hp=hp
self.attack=attack
def set_hp(self,hp):
if 100<=hp<=200:
self.__hp = hp
else:
raise ValueError("超出范围")
def get_hp(self):
return self.__hp
hp = property(get_hp,set_hp)
def set_attack(self, attack):
if 10 <= attack <= 50:
self.__attack = attack
else:
raise ValueError("超出范围")
def get_attack(self):
return self.__attack
attack = property(get_attack,set_attack)
enemy = Enemy("ni",100,15)
print(enemy.hp)
最终推荐写法
需要对实例变量进行逻辑上的限制
class Enemy:
def __init__(self,name,hp,attack):
self.name = name
self.hp = hp
self.attack=attack
@property #创建property对象,只负责拦截类变量hp的读取操作
def hp(self):
return self.__hp
@hp.setter #只负责拦截类变量hp的设置操作
def hp(self,value):
if 100<=value<=200:
self.__hp = value
else:
raise ValueError("超出范围")
@property
def attack(self):
return self.__attack
@attack.setter
def attack(self, attack):
if 10 <= attack <= 50:
self.__attack = attack
else:
raise ValueError("超出范围")
enemy = Enemy("ni",150,15)
enemy.hp=100
print(enemy.__dict__)
print(enemy.hp)
内存图