1. 程式人生 > >@property 用法

@property 用法

return attack 實例 per nds pre seconds 方法 under

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 這個實例屬性來訪問

@property 用法