【python 面向对象 class 封装】
class Wife02():
def __init__(self,name,age,sex):
self.set_name(name)
self.set_age(age)
self.set_sex(sex)
def set_name(self,value):
if isinstance(value,str):
if '\u4e00' <= value <= '\u9fff':
self.__name = value
else:
raise ValueError("不是中国人")
else:
raise ValueError("数据类型错误")
def set_age(self,value):
if 18 <= value <= 100:
self.__age = value
else:
raise ValueError("年龄不符,请重新创建对象")
def set_sex(self,value):
if value == "女":
self.__sex = value
else:
raise ValueError("性别错误")
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def get_sex(self):
return self.__sex
w04 = Wife02("张三",20,"女")
print(w04._Wife02__age)
print(w04.get_age())
print(w04.__dict__)
w04.set_age(30)
print(w04.__dict__)
w04.sex = "男"
print(w04.__dict__)
class Wife03():
__slots__ = ("__age","sex")
def __init__(self,age,sex = ""):
self.age = age
self.sex = sex
@property
def age(self):
return self.__age
@age.setter
def age(self,value):
if 18 <= value <= 100:
self.__age = value
else:
raise ValueError("年龄不符,请重新创建对象")
w05 = Wife03(30)
print(w05.age)
w05 = Wife03(20)
print(w05.age)
print(w05.__slots__)
print(w05._Wife03__age)
print(dir(w05))
class Person:
def __init__(self, name):
self.name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
def go_home(self, car):
print(self.name, end="")
car.run("家")
class Car:
def run(self, pos):
print("移动到" + pos)
zs = Person("张三")
car = Car()
zs.go_home(car)
|