#静态方法用的少,相当于类的工具包,访问不了类或实例中的任何属性
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。