您好,登錄后才能下訂單哦!
#靜態(tài)方法用的少,相當于類的工具包,訪問不了類或?qū)嵗械娜魏螌傩?/span>
class Dog(object):
def __init__(self,name):
self.name=name
@staticmethod#實際上跟類沒關(guān)系了,就只是一個函數(shù)了,名義上歸類管
def eat(self):
print("%s is eating %s"%(self.name,'dd'))
def talk(self):
print("%s is talking"%self.name)
d=Dog("chenronghua")
d.eat(d) #把自己傳到eat函數(shù),使self有效
d.talk()
#類方法基本用不到
class Dog(object):
name="huazai"
def __init__(self,name):
self.name=name
self.n=2222
@classmethod #類方法只能訪問類變量,不能訪問實例變量
def eat(self):
print("%s is eating %s"%(self.name,'dd'))
def talk(self):
print("%s is talking"%self.name)
d=Dog("chenronghua")
d.eat()
d.talk()
#屬性方法
class Dog(object):
def __init__(self,name):
self.name=name
@property
def eat(self):
print("%s is eating %s"%(self.name,'dd'))
@eat.setter
def eat(self,food):
print("set to food:",food)
d=Dog("chenronghua")
d.eat # @property下面的eat
d.eat="baozi" # @eat.setter 傳入food
--————————————————————————————————————————
class Dog(object):
def __init__(self,name):
self.name=name
self.__food=None #空變量
@property #方法轉(zhuǎn)屬性(函數(shù)轉(zhuǎn)變量)
def eat(self):
print("%s is eating %s"%(self.name,self.__food)) #先傳一個空變量 self.__food
@eat.setter #修改 修改food值
def eat(self,food): #修改 修改food值
print("set to food:",food)
self.__food=food #將food傳入 空變量
@eat.deleter #刪除
def eat(self):
del self.__food
print("刪完了")
d=Dog("chenronghua")
d.eat # @property下面的eat
d.eat="baozi" # @eat.setter 傳入food
d.eat # "baozi"傳入self.__food,@property下面的 food是"baozi"
del d.eat # @eat,deleter 刪除eat函數(shù) del self.__food刪除self.__food變量
d.eat #依然調(diào)用@property下的eat 提示刪除了Dog.__food變量 即self.__food
# @property
#def eat(self):
# print("%s is eating %s"%(self.name,self.__food))
#屬性方法實例
class Flight(object):
def __init__(self, name):
self.flight_name = name
def checking_status(self):
print("checking flight %s status " % self.flight_name)
return 2
@property #航班狀態(tài)方法轉(zhuǎn)變成屬性方法
def flight_status(self):
status = self.checking_status()
if status == 0:
print("flight got canceled...")
elif status == 1:
print("flight is arrived...")
elif status == 2:
print("flight has departured already...")
else:
print("cannot confirm the flight status...,please check later")
@flight_status.setter # 修改航班狀態(tài)
def flight_status(self, status):
print("flight %s has changed the flight status to %s"%(self.flight_name,status))
@flight_status.deleter # 刪除航班狀態(tài)
def flight_status(self):
print("status got removed...")
f = Flight("CA980")
f.flight_status
f.flight_status = 2 # 觸發(fā)@flight_status.setter
#del f.flight_status # 觸發(fā)@flight_status.deleter
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。