本節內容:html
把下面代碼用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:程序員
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
5
|
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'
<
/
module>
|
想讓上面的代碼能夠正常工做有兩種辦法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裝飾器實現,類方法和普通方法的區別是, 類方法只能訪問類變量,不能訪問實例變量3d
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,看下執行效果
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把一個方法變成一個靜態屬性
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
|
正常調用以下
d
=
Dog(
"ChenRonghua"
)
d.eat
輸出
ChenRonghua
is
eating
|
好吧,把一個方法變成靜態屬性有什麼卵用呢?既然想要靜態變量,那直接定義成一個靜態變量不就得了麼?well, 之後你會需到不少場景是不能簡單經過 定義 靜態屬性來實現的, 好比 ,你想知道一個航班當前的狀態,是到達了、延遲了、取消了、仍是已經飛走了, 想知道這種狀態你必須經歷如下幾步:
1. 鏈接航空公司API查詢
2. 對查詢結果進行解析
3. 返回結果給你的用戶
所以這個status屬性的值是一系列動做後才獲得的結果,因此你每次調用時,其實它都要通過一系列的動做才返回你結果,但這些動做過程不須要用戶關心, 用戶只須要調用這個屬性就能夠,明白 了麼?
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 25 26 航班查詢
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進行更改。
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 11 @property 12 def flight_status(self): 13 status = self.checking_status() 14 if status == 0 : 15 print("flight got canceled...") 16 elif status == 1 : 17 print("flight is arrived...") 18 elif status == 2: 19 print("flight has departured already...") 20 else: 21 print("cannot confirm the flight status...,please check later") 22 23 @flight_status.setter #修改 24 def flight_status(self,status): 25 status_dic = { 26 : "canceled", 27 :"arrived", 28 : "departured" 29 } 30 print("\033[31;1mHas changed the flight status to \033[0m",status_dic.get(status) ) 31 32 @flight_status.deleter #刪除 33 def flight_status(self): 34 print("status got removed...") 35 36 f = Flight("CA980") 37 f.flight_status 38 f.flight_status = 2 #觸發@flight_status.setter 39 del f.flight_status #觸發@flight_status.deleter
注意以上代碼裏還寫了一個@flight_status.deleter, 是容許能夠將這個屬性刪除
1 class Foo: 2 """ 描述類信息,這是用於看片的神奇 """ 3 4 def func(self): 5 pass 6 7 print Foo.__doc__ 8 #輸出:類的描述信息
__module__ 表示當前操做的對象在那個模塊
__class__ 表示當前操做的對象的類是什麼
1 class C: 2 3 def __init__(self): 4 self.name = 'wupeiqi'
1 from lib.aa import C 2 3 obj = C() 4 print obj.__module__ # 輸出 lib.aa,即:輸出模塊 5 print obj.__class__ # 輸出 lib.aa.C,即:輸出類
析構方法,當對象在內存中被釋放時,自動觸發執行。
注:此方法通常無須定義,由於Python是一門高級語言,程序員在使用時無需關心內存的分配和釋放,由於此工做都是交給Python解釋器來執行,因此,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的
5. __call__ 對象後面加括號,觸發執行。
注:構造方法的執行是由建立對象觸發的,即:對象 = 類名() ;而對於 __call__ 方法的執行是由對象後加括號觸發的,即:對象() 或者 類()()
1 class Foo: 2 3 def __init__(self): 4 pass 5 6 def __call__(self, *args, **kwargs): 7 8 print '__call__' 9 10 11 obj = Foo() # 執行 __init__ 12 obj() # 執行 __call__
1 class Province: 2 3 country = 'China' 4 5 def __init__(self, name, count): 6 self.name = name 7 self.count = count 8 9 def func(self, *args, **kwargs): 10 print 'func' 11 12 # 獲取類的成員,即:靜態字段、方法、 13 print Province.__dict__ 14 # 輸出:{'country': 'China', '__module__': '__main__', 'func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__': None} 15 16 obj1 = Province('HeBei',10000) 17 print obj1.__dict__ 18 # 獲取 對象obj1 的成員 19 # 輸出:{'count': 10000, 'name': 'HeBei'} 20 21 obj2 = Province('HeNan', 3888) 22 print obj2.__dict__ 23 # 獲取 對象obj1 的成員 24 # 輸出:{'count': 3888, 'name': 'HeNan'}
1 class Foo: 2 3 def __str__(self): 4 return 'alex li' 5 6 7 obj = Foo() 8 print obj 9 # 輸出:alex li
用於索引操做,如字典。以上分別表示獲取、設置、刪除數據
1 class Foo(object): 2 3 def __getitem__(self, key): 4 print('__getitem__',key) 5 6 def __setitem__(self, key, value): 7 print('__setitem__',key,value) 8 9 def __delitem__(self, key): 10 print('__delitem__',key) 11 12 13 obj = Foo() 14 15 result = obj['k1'] # 自動觸發執行 __getitem__ 16 obj['k2'] = 'alex' # 自動觸發執行 __setitem__ 17 del obj['k1']
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第三個參數:類的成員
|
1 def func(self): 2 print("hello %s"%self.name) 3 4 def __init__(self,name,age): 5 self.name = name 6 self.age = age 7 Foo = type('Foo',(object,),{'func':func,'__init__':__init__}) 8 9 f = Foo("jack",22) 10 f.func() 11 12 加上構造方法
So ,孩子記住,類 是由 type 類實例化產生
那麼問題來了,類默認是由 type 類實例化產生,type類中如何實現的建立類?類又是如何建立對象?
答:類中有一個屬性 __metaclass__,其用來表示該類由 誰 來實例化建立,因此,咱們能夠爲 __metaclass__ 設置一個type類的派生類,從而查看 類 建立的過程。
1 #_*_coding:utf-8_*_ 2 3 class MyType(type): 4 def __init__(self, child_cls, bases=None, dict=None): 5 print("--MyType init---", child_cls,bases,dict) 6 #super(MyType, self).__init__(child_cls, bases, dict) 7 8 # def __new__(cls, *args, **kwargs): 9 # print("in mytype new:",cls,args,kwargs) 10 # type.__new__(cls) 11 def __call__(self, *args, **kwargs): 12 print("in mytype call:", self,args,kwargs) 13 obj = self.__new__(self,args,kwargs) 14 15 self.__init__(obj,*args,**kwargs) 16 17 class Foo(object,metaclass=MyType): #in python3 18 #__metaclass__ = MyType #in python2 19 20 def __init__(self, name): 21 self.name = name 22 print("Foo ---init__") 23 24 def __new__(cls, *args, **kwargs): 25 print("Foo --new--") 26 return object.__new__(cls) 27 28 def __call__(self, *args, **kwargs): 29 print("Foo --call--",args,kwargs) 30 # 第一階段:解釋器從上到下執行代碼建立Foo類 31 # 第二階段:經過Foo類建立obj對象 32 obj = Foo("Alex") 33 #print(obj.name) 34 35 自定義元類
類的生成 調用 順序依次是 __new__ --> __call__ --> __init__
metaclass 詳解文章:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 得票最高那個答案寫的很是好
經過字符串映射或修改程序運行時的狀態、屬性、方法, 有如下4個方法
1 def getattr(object, name, default=None): # known special case of getattr 2 """ 3 getattr(object, name[, default]) -> value 4 5 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. 6 When a default argument is given, it is returned when the attribute doesn't 7 exist; without it, an exception is raised in that case. 8 """ 9 pass 10 11 getattr(object, name, default=None)
判斷object中有沒有一個name字符串對應的方法或屬性(hasattr(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''
1 def delattr(x, y): # real signature unknown; restored from __doc__ 2 """ 3 Deletes the named attribute from the given object. 4 5 delattr(x, 'y') is equivalent to ``del x.y'' 6 """ 7 8 delattr(x, y)
1 class Foo(object): 2 3 def __init__(self): 4 self.name = 'wupeiqi' 5 6 def func(self): 7 return 'func' 8 9 obj = Foo() 10 11 # #### 檢查是否含有成員 #### 12 hasattr(obj, 'name') 13 hasattr(obj, 'func') 14 15 # #### 獲取成員 #### 16 getattr(obj, 'name') 17 getattr(obj, 'func') 18 19 # #### 設置成員 #### 20 setattr(obj, 'age', 18) 21 setattr(obj, 'show', lambda num: num + 1) 22 23 # #### 刪除成員 #### 24 delattr(obj, 'name') 25 delattr(obj, 'func') 26 27 反射代碼示例
動態導入模塊
import
importlib
__import__
(
'import_lib.metaclass'
)
#這是解釋器本身內部用的
#importlib.import_module('import_lib.metaclass') #與上面這句效果同樣,官方建議用這個
參考 http://www.cnblogs.com/wupeiqi/articles/5017742.html
參考:http://www.cnblogs.com/wupeiqi/articles/5040823.html
做業:開發一個支持多用戶在線的FTP程序
要求: