python 类(3) property
程序员文章站
2022-08-17 17:50:28
class PetCat(): """ 家猫类""" def __init__(self, name, age): self.name = name # 私有属性 self.__age = age @property def age(self): return self.__age @age.set ......
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)
上一篇: 企业怎样设计网站主题及风格
下一篇: leetcode求峰值,js实现