import datetimeimport time class PK(object): def __init__(self,name,attack=0.0,defence=0.0): self.name = name self.attack = attack self.defence = defence self._obtain_time = datetime.datetime.now() @property def defence(self): return self._defence @defence.setter def defence(self,value): if value < 0 : print("防御值小于0设置为0") self._defence = 0 elif value > 1000: print("防御值大于1000被设置为1000") self._defence = 1000 else: self._defence = value @property def age(self): return (datetime.datetime.now() - self._obtain_time).seconds a = PK("铠甲",defence=10000)print(a.defence)a.defence = -100print(a.age)time.sleep(1)print(a.age) @property 是把方法变为属性,_one_underline 标识这个是私有不应该直接被访问,不属于API,但可以通过defence 这个实例属性来访问
原文地址:https://www.cnblogs.com/wudeng/p/9299377.html
时间: 2024-10-14 10:53:11