python 类(3) property



class PetCat():
""" 家猫类"""

def __init__(self, name, age):
self.name = name
# 私有属性
self.__age = age

@property
def age(self):
return self.__age

@age.setter
def age(self,value):
if not isinstance(value, int):
print('年龄只能是整数')
return 0
if value < 0 or value > 100:
print('年龄只能介于0-100之间')
return 0
self.__age = value

# 描述符
@property
def show_info(self):
return "我叫{0},今年{1}岁".format(self.name,self.age)

def __str__(self):
# return self.show_info()
return '---'

if __name__ == '__main__':
cat_black = PetCat('小黑', 2)
rest = cat_black.show_info
print(rest)
# print('-------------')
# print(cat_black) #我叫小黑,今年2岁
cat_black.age = 6
rest = cat_black.show_info
print(rest)
上一篇:LightOJ 1186 Icreable Chess(Nim博弈)


下一篇:1135 Is It A Red-Black Tree (30 分)