本篇内容:
面向对象、类方法、属性方法
类的特殊方法
反射
异常处理
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 @property 11 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("