首页 > 代码库 > python之路,day7-面向对象变成
python之路,day7-面向对象变成
本篇内容:
面向对象、类方法、属性方法
类的特殊方法
反射
异常处理
Socket开发基础
一、面向对象高级语法部分
静态方法:
#@staticmethod只是名义上归类管理,实际上跟类没什么关系
class Dog(object): def __init__(self,name): self.name = name @staticmethod #把eat方法变为静态方法 def eat(self): print("%s is eating" % self.name) d = Dog("user")d.eat()
上面的调用会出以下错误,说是eat需要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。
1. 调用时主动传递实例本身给eat方法,即d.eat(d)
2. 在eat方法中去掉self参数,但这也意味着,在eat中不能通过self.调用实例中的其它变量了
class Dog(object): def __init__(self,name): self.name = name @staticmethod def eat(): print(" is eating") d = Dog("user")d.eat()
二、类方法
#@classmethod
只能访问类变量,不能访问实例变量
class Dog(object): name = "类变量" def __init__(self,name): self.name = name @classmethod def eat(self): print("%s is eating" % self.name) d = Dog("user")d.eat() #执行结果: 类变量 is eating
三、属性方法
#@proprty 把一个方法变成一个静态属性
#@eat.setter 更改属性
#@eat.deleter 删除属性
class Dog(object): def __init__(self,name): self.name = name @property def eat(self): print(" %s is eating" %self.name) d = Dog("user")d.eat#输出结果:user is eating
列:
1 class Flight(object): 2 def __init__(self,name): 3 self.flight_name = name 4 5 6 def checking_status(self): 7 print("checking flight %s status " % self.flight_name) 8 return 1 9 10 @property11 def flight_status(self):12 status = self.checking_status()13 if status == 0 :14 print("flight got canceled...")15 elif status == 1 :16 print("flight is arrived...")17 elif status == 2:18 print("flight has departured already...")19 else:20 print("cannot confirm the flight status...,please check later")21 22 23 f = Flight("CA980")24 f.flight_status
列2:@proerty.setter装饰器再装饰一下,需要写一个新方法, 对这个flight_status进行更改。
class Flight(object): def __init__(self,name): self.flight_name = name def checking_status(self): print("checking flight %s status " % self.flight_name) return 1 @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): status_dic = {: "canceled",:"arrived",: "departured" } print("\033[31;1mHas changed the flight status to \033[0m",status_dic.get(status) ) @flight_status.deleter #删除 def flight_status(self): print("status got removed...")f = Flight("CA980")f.flight_statusf.flight_status = 2 #触发@flight_status.setter del f.flight_status #触发@flight_status.deleter
注意以上代码里还写了一个@flight_status.deleter, 是允许可以将这个属性删除
四:类的特殊成员
python之路,day7-面向对象变成
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。