欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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)