静态方法,类方法,属性方法,属性方法实例-创新互联
#静态方法用的少,相当于类的工具包,访问不了类或实例中的任何属性
classDog(object):
def__init__(self,name):
self.name=name
@staticmethod#实际上跟类没关系了,就只是一个函数了,名义上归类管
defeat(self):
print("%s is eating %s"%(self.name,'dd'))
deftalk(self):
print("%s is talking"%self.name)
d=Dog("chenronghua")
d.eat(d) #把自己传到eat函数,使self有效
d.talk()
#类方法基本用不到
classDog(object):
name="huazai"
def__init__(self,name):
self.name=name
self.n=2222
@classmethod #类方法只能访问类变量,不能访问实例变量
defeat(self):
print("%s is eating %s"%(self.name,'dd'))
deftalk(self):
print("%s is talking"%self.name)
d=Dog("chenronghua")
d.eat()
d.talk()
#属性方法
classDog(object):
def__init__(self,name):
self.name=name
@property
defeat(self):
print("%s is eating %s"%(self.name,'dd'))
@eat.setter
defeat(self,food):
print("set to food:",food)
d=Dog("chenronghua")
d.eat # @property下面的eat
d.eat="baozi"# @eat.setter 传入food
--————————————————————————————————————————
classDog(object):
def__init__(self,name):
self.name=name
self.__food=None#空变量
@property #方法转属性(函数转变量)
defeat(self):
print("%s is eating %s"%(self.name,self.__food)) #先传一个空变量 self.__food
@eat.setter #修改 修改food值
defeat(self,food): #修改 修改food值
print("set to food:",food)
self.__food=food #将food传入 空变量
@eat.deleter #删除
defeat(self):
delself.__food
print("删完了")
d=Dog("chenronghua")
d.eat # @property下面的eat
d.eat="baozi"# @eat.setter 传入food
d.eat # "baozi"传入self.__food,@property下面的 food是"baozi"
deld.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))
#属性方法实例
classFlight(object):
def__init__(self, name):
self.flight_name = name
defchecking_status(self):
print("checking flight %s status "% self.flight_name)
return2
@property #航班状态方法转变成属性方法
defflight_status(self):
status = self.checking_status()
ifstatus == 0:
print("flight got canceled...")
elifstatus == 1:
print("flight is arrived...")
elifstatus == 2:
print("flight has departured already...")
else:
print("cannot confirm the flight status...,please check later")
@flight_status.setter # 修改航班状态
defflight_status(self, status):
print("flight %s has changed the flight status to %s"%(self.flight_name,status))
@flight_status.deleter # 删除航班状态
defflight_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
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
名称栏目:静态方法,类方法,属性方法,属性方法实例-创新互联
转载注明:http://scjbc.cn/article/depphe.html