您好,登錄后才能下訂單哦!
#靜態方法用的少,相當于類的工具包,訪問不了類或實例中的任何屬性
class Dog(object):
def __init__(self,name):
self.name=name
@staticmethod#實際上跟類沒關系了,就只是一個函數了,名義上歸類管
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函數,使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 #方法轉屬性(函數轉變量)
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函數 del self.__food刪除self.__food變量
d.eat #依然調用@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 #航班狀態方法轉變成屬性方法
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 # 修改航班狀態
def flight_status(self, status):
print("flight %s has changed the flight status to %s"%(self.flight_name,status))
@flight_status.deleter # 刪除航班狀態
def flight_status(self):
print("status got removed...")
f = Flight("CA980")
f.flight_status
f.flight_status = 2 # 觸發@flight_status.setter
#del f.flight_status # 觸發@flight_status.deleter
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。