Day7 - Python基礎7 面向對象編程進階 --轉自金角大王

本節內容:html

  • 面向對象高級語法部分
    • 經典類vs新式類  
    • 靜態方法、類方法、屬性方法
    • 類的特殊方法
    • 反射
  • 異常處理
  • Socket開發基礎
  • 做業:開發一個支持多用戶在線的FTP程序

  

面向對象高級語法部分

經典類vs新式類

把下面代碼用python2 和python3都執行一下python

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#_*_coding:utf-8_*_
 
 
class A:
     def __init__( self ):
         self .n = 'A'
 
class B(A):
     # def __init__(self):
     #     self.n = 'B'
     pass
 
class C(A):
     def __init__( self ):
         self .n = 'C'
 
class D(B,C):
     # def __init__(self):
     #     self.n = 'D'
     pass
 
obj = D()
 
print (obj.n)

classical vs new style:程序員

  • 經典類:深度優先
  • 新式類:廣度優先
  • super()用法

 

抽象接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import abc
 
class Alert( object ):
     '''報警基類'''
     __metaclass__ = abc.ABCMeta
 
     @abc .abstractmethod
     def send( self ):
         '''報警消息發送接口'''
         pass
 
 
 
class MailAlert(Alert):
     pass
 
 
m = MailAlert()
m.send()

上面的代碼僅在py2裏有效,python3裏怎麼實現呢?編程

  

 

 

 

  

靜態方法

經過@staticmethod裝飾器便可把其裝飾的方法變爲一個靜態方法,什麼是靜態方法呢?其實不難理解,普通的方法,能夠在實例化後直接調用,而且在方法裏能夠經過self.調用實例變量或類變量,但靜態方法是不能夠訪問實例變量或類變量的,一個不能訪問實例變量和類變量的方法,其實至關於跟類自己已經沒什麼關係了,它與類惟一的關聯就是須要經過類名來調用這個方法ide

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class Dog( object ):
 
     def __init__( self ,name):
         self .name = name
 
     @staticmethod #把eat方法變爲靜態方法
     def eat( self ):
         print ( "%s is eating" % self .name)
 
 
 
d = Dog( "ChenRonghua" )
d.eat()

上面的調用會出如下錯誤,說是eat須要一個self參數,但調用時卻沒有傳遞,沒錯,當eat變成靜態方法後,再經過實例調用時就不會自動把實例自己看成一個參數傳給self了。函數

?
1
2
3
4
Traceback (most recent call last):
   File "/Users/jieli/PycharmProjects/python基礎/自動化day7面向對象高級/靜態方法.py" , line 17 , in <module>
     d.eat()
TypeError: eat() missing 1 required positional argument: 'self'

想讓上面的代碼能夠正常工做有兩種辦法ui

1. 調用時主動傳遞實例自己給eat方法,即d.eat(d) 加密

2. 在eat方法中去掉self參數,但這也意味着,在eat中不能經過self.調用實例中的其它變量了spa

複製代碼
複製代碼
 1 class Dog(object):  2  3 def __init__(self,name):  4 self.name = name  5  6  @staticmethod  7 def eat():  8 print(" is eating")  9 10 11 12 d = Dog("ChenRonghua") 13 d.eat()
複製代碼
複製代碼

 

類方法  

類方法經過@classmethod裝飾器實現,類方法和普通方法的區別是, 類方法只能訪問類變量,不能訪問實例變量rest

?
1
2
3
4
5
6
7
8
9
10
11
12
class Dog( object ):
     def __init__( self ,name):
         self .name = name
 
     @classmethod
     def eat( self ):
         print ( "%s is eating" % self .name)
 
 
 
d = Dog( "ChenRonghua" )
d.eat()

執行報錯以下,說Dog沒有name屬性,由於name是個實例變量,類方法是不能訪問實例變量的

?
1
2
3
4
5
6
Traceback (most recent call last):
   File "/Users/jieli/PycharmProjects/python基礎/自動化day7面向對象高級/類方法.py" , line 16 , in <module>
     d.eat()
   File "/Users/jieli/PycharmProjects/python基礎/自動化day7面向對象高級/類方法.py" , line 11 , in eat
     print ( "%s is eating" % self .name)
AttributeError: type object 'Dog' has no attribute 'name'

此時能夠定義一個類變量,也叫name,看下執行效果

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog( object ):
     name = "我是類變量"
     def __init__( self ,name):
         self .name = name
 
     @classmethod
     def eat( self ):
         print ( "%s is eating" % self .name)
 
 
 
d = Dog( "ChenRonghua" )
d.eat()
 
 
#執行結果
 
我是類變量 is eating

 

屬性方法  

屬性方法的做用就是經過@property把一個方法變成一個靜態屬性

?
1
2
3
4
5
6
7
8
9
10
11
12
class Dog( object ):
 
     def __init__( self ,name):
         self .name = name
 
     @property
     def eat( self ):
         print ( " %s is eating" % self .name)
 
 
d = Dog( "ChenRonghua" )
d.eat()

調用會出如下錯誤, 說NoneType is not callable, 由於eat此時已經變成一個靜態屬性了, 不是方法了, 想調用已經不須要加()號了,直接d.eat就能夠了

?
1
2
3
4
5
Traceback (most recent call last):
  ChenRonghua is eating
   File "/Users/jieli/PycharmProjects/python基礎/自動化day7面向對象高級/屬性方法.py" , line 16 , in <module>
     d.eat()
TypeError: 'NoneType' object is not callable

正常調用以下

?
1
2
3
4
5
d = Dog( "ChenRonghua" )
d.eat
 
輸出
  ChenRonghua is eating

好吧,把一個方法變成靜態屬性有什麼卵用呢?既然想要靜態變量,那直接定義成一個靜態變量不就得了麼?well, 之後你會需到不少場景是不能簡單經過 定義 靜態屬性來實現的, 好比 ,你想知道一個航班當前的狀態,是到達了、延遲了、取消了、仍是已經飛走了, 想知道這種狀態你必須經歷如下幾步:

1. 鏈接航空公司API查詢

2. 對查詢結果進行解析 

3. 返回結果給你的用戶

所以這個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") f = Flight("CA980") f.flight_status
複製代碼

cool , 那如今我只能查詢航班狀態, 既然這個flight_status已是個屬性了, 那我可否給它賦值呢?試試吧

?
1
2
3
f = Flight( "CA980" )
f.flight_status
f.flight_status =  2

輸出, 說不能更改這個屬性,我擦。。。。,怎麼辦怎麼辦。。。 

?
1
2
3
4
5
6
checking flight CA980 status
flight is arrived...
Traceback (most recent call last):
   File "/Users/jieli/PycharmProjects/python基礎/自動化day7面向對象高級/屬性方法.py" , line 58 , in <module>
     f.flight_status =  2
AttributeError: can't set attribute

固然能夠改, 不過須要經過@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 = { 0 : "canceled", 1 :"arrived", 2 : "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_status f.flight_status = 2 #觸發@flight_status.setter del f.flight_status #觸發@flight_status.deleter 
複製代碼

注意以上代碼裏還寫了一個@flight_status.deleter, 是容許能夠將這個屬性刪除 

 

類的特殊成員方法

1. __doc__  表示類的描述信息

2. __module__ 和  __class__ 

  __module__ 表示當前操做的對象在那個模塊

  __class__     表示當前操做的對象的類是什麼

class C: def __init__(self): self.name = 'wupeiqi'
from lib.aa import C obj = C() print obj.__module__ # 輸出 lib.aa,即:輸出模塊 print obj.__class__ # 輸出 lib.aa.C,即:輸出類

3. __init__ 構造方法,經過類建立對象時,自動觸發執行。

4.__del__

 析構方法,當對象在內存中被釋放時,自動觸發執行。

注:此方法通常無須定義,由於Python是一門高級語言,程序員在使用時無需關心內存的分配和釋放,由於此工做都是交給Python解釋器來執行,因此,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的

  

 5. __call__ 對象後面加括號,觸發執行。

注:構造方法的執行是由建立對象觸發的,即:對象 = 類名() ;而對於 __call__ 方法的執行是由對象後加括號觸發的,即:對象() 或者 類()()

6. __dict__ 查看類或對象中的全部成員   

7.__str__ 若是一個類中定義了__str__方法,那麼在打印 對象 時,默認輸出該方法的返回值。

8.__getitem__、__setitem__、__delitem__

用於索引操做,如字典。以上分別表示獲取、設置、刪除數據

9. __new__ \ __metaclass__

?
1
2
3
4
5
6
7
8
class Foo( object ):
 
 
     def __init__( self ,name):
         self .name = name
 
 
f = Foo( "alex" )

上述代碼中,obj 是經過 Foo 類實例化的對象,其實,不只 obj 是一個對象,Foo類自己也是一個對象,由於在Python中一切事物都是對象

若是按照一切事物都是對象的理論:obj對象是經過執行Foo類的構造方法建立,那麼Foo類對象應該也是經過執行某個類的 構造方法 建立。

?
1
2
print type (f) # 輸出:<class '__main__.Foo'>     表示,obj 對象由Foo類建立
print type (Foo) # 輸出:<type 'type'>              表示,Foo類對象由 type 類建立

因此,f對象是Foo類的一個實例Foo類對象是 type 類的一個實例,即:Foo類對象 是經過type類的構造方法建立。

那麼,建立類就能夠有兩種方式:

a). 普通方式 

?
1
2
3
4
class Foo( object ):
  
     def func( self ):
         print 'hello alex'

b). 特殊方式

?
1
2
3
4
5
6
7
def func( self ):
     print 'hello wupeiqi'
  
Foo = type ( 'Foo' ,( object ,), { 'func' : func})
#type第一個參數:類名
#type第二個參數:當前類的基類
#type第三個參數:類的成員
複製代碼
def func(self): print("hello %s"%self.name) def __init__(self,name,age): self.name = name self.age = age Foo = type('Foo',(object,),{'func':func,'__init__':__init__}) f = Foo("jack",22) f.func()
複製代碼

So ,孩子記住,類 是由 type 類實例化產生

那麼問題來了,類默認是由 type 類實例化產生,type類中如何實現的建立類?類又是如何建立對象?

答:類中有一個屬性 __metaclass__,其用來表示該類由 誰 來實例化建立,因此,咱們能夠爲 __metaclass__ 設置一個type類的派生類,從而查看 類 建立的過程。

 

複製代碼
 1 class MyType(type):  2 def __init__(self,*args,**kwargs):  3  4 print("Mytype __init__",*args,**kwargs)  5  6 def __call__(self, *args, **kwargs):  7 print("Mytype __call__", *args, **kwargs)  8 obj = self.__new__(self)  9 print("obj ",obj,*args, **kwargs) 10 print(self) 11 self.__init__(obj,*args, **kwargs) 12 return obj 13 14 def __new__(cls, *args, **kwargs): 15 print("Mytype __new__",*args,**kwargs) 16 return type.__new__(cls, *args, **kwargs) 17 18 print('here...') 19 class Foo(object,metaclass=MyType): 20 21 22 def __init__(self,name): 23 self.name = name 24 25 print("Foo __init__") 26 27 def __new__(cls, *args, **kwargs): 28 print("Foo __new__",cls, *args, **kwargs) 29 return object.__new__(cls) 30 31 f = Foo("Alex") 32 print("f",f) 33 print("fname",f.name)
複製代碼

 

 

 類的生成 調用 順序依次是 __new__ --> __init__ --> __call__

 metaclass 詳解文章:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 得票最高那個答案寫的很是好

 

反射

經過字符串映射或修改程序運行時的狀態、屬性、方法, 有如下4個方法

複製代碼
def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass
複製代碼
判斷object中有沒有一個name字符串對應的方法或屬性
def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v''
def delattr(x, y): # real signature unknown; restored from __doc__ """ Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' """
複製代碼
class Foo(object): def __init__(self): self.name = 'wupeiqi' def func(self): return 'func' obj = Foo() # #### 檢查是否含有成員 #### hasattr(obj, 'name') hasattr(obj, 'func') # #### 獲取成員 #### getattr(obj, 'name') getattr(obj, 'func') # #### 設置成員 #### setattr(obj, 'age', 18) setattr(obj, 'show', lambda num: num + 1) # #### 刪除成員 #### delattr(obj, 'name') delattr(obj, 'func')
複製代碼

 

 

動態導入模塊

 

 

?
1
2
3
4
import importlib
 
__import__ ( 'import_lib.metaclass' ) #這是解釋器本身內部用的
#importlib.import_module('import_lib.metaclass') #與上面這句效果同樣,官方建議用這個

 

  

異常處理 

參考 http://www.cnblogs.com/wupeiqi/articles/5017742.html   

 

 

Socket 編程

參考:http://www.cnblogs.com/wupeiqi/articles/5040823.html

 

 

做業:開發一個支持多用戶在線的FTP程序

 

要求:

 

  1. 用戶加密認證
  2. 容許同時多用戶登陸
  3. 每一個用戶有本身的家目錄 ,且只能訪問本身的家目錄
  4. 對用戶進行磁盤配額,每一個用戶的可用空間不一樣
  5. 容許用戶在ftp server上隨意切換目錄
  6. 容許用戶查看當前目錄下文件
  7. 容許上傳和下載文件,保證文件一致性
  8. 文件傳輸過程當中顯示進度條
  9. 附加功能:支持文件的斷點續傳
相關文章
相關標籤/搜索