@property 用法

import datetime
import 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 = -100
print(a.age)
time.sleep(1)
print(a.age)

@property 是把方法变为属性,_one_underline 标识这个是私有不应该直接被访问,不属于API,但可以通过defence 这个实例属性来访问
posted @ 2018-07-12 14:44  五等码农  阅读(138)  评论(0编辑  收藏  举报