日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

深入講解Python中面向?qū)ο缶幊痰南嚓P(guān)知識(shí)

系統(tǒng) 2259 0

?Python從第一天開始就是面向?qū)ο蟮恼Z言。正因?yàn)槿绱耍瑒?chuàng)建和使用類和對(duì)象是非常地容易。本章將幫助您在使用Python面向?qū)ο缶幊痰募夹g(shù)方面所有提高。

如果沒有任何以往面向?qū)ο?OO)的編程的經(jīng)驗(yàn),那么可能要了解一些基本的入門課程就可以了,或者至少某種形式的教程,讓你有了解基本概念。

但是,這里會(huì)比較少地介紹面向?qū)ο缶幊?OOP):
OOP術(shù)語概述

  • ??? 類: 用戶定義的原型對(duì)象,它定義了一套描述類的任何對(duì)象的屬性。屬性是數(shù)據(jù)成員(類變量和實(shí)例變量)和方法,通過點(diǎn)符號(hào)訪問。
  • ??? 類變量:這是一個(gè)類的所有實(shí)例共享的變量。類變量在類,但外面的任何類的方法定義。類變量不被用作經(jīng)常作為實(shí)例變量。
  • ??? 數(shù)據(jù)成員:保存與類和對(duì)象關(guān)聯(lián)的數(shù)據(jù)的類變量或?qū)嵗兞俊?
  • ??? 函數(shù)重載:一個(gè)以上的行為特定功能的分配。執(zhí)行的操作所涉及的對(duì)象(自變量)的類型不同而不同。
  • ??? 實(shí)例變量:所定義的方法內(nèi),只屬于一個(gè)類的當(dāng)前實(shí)例的變量。
  • ??? 繼承:類的特點(diǎn),即都是由它派生其他類的轉(zhuǎn)移。
  • ??? 實(shí)例:某一類的一個(gè)單獨(dú)對(duì)象。屬于類Circle一個(gè)obj對(duì)象,例如,是類Circle的一個(gè)實(shí)例。
  • ??? 實(shí)例化:創(chuàng)建一個(gè)類的實(shí)例。
  • ??? Method : 一種特殊的函數(shù),函數(shù)在類定義中定義。
  • ??? 對(duì)象:這是由它的類中定義的數(shù)據(jù)結(jié)構(gòu)的唯一實(shí)例。一個(gè)對(duì)象包括兩個(gè)數(shù)據(jù)成員(類變量和實(shí)例變量)和方法。
  • ??? 運(yùn)算符重載:一個(gè)以上的函數(shù)功能,特定的操作符分配。

創(chuàng)建類:

類語句將創(chuàng)建一個(gè)新的類定義。類的名稱緊跟在關(guān)鍵字class后跟一個(gè)冒號(hào),如下所示:

            
class ClassName:
  'Optional class documentation string'
  class_suite


          

??? 類有一個(gè)文檔字符串,它可以通過類名.__ doc__訪問。

??? class_suite由所有定義的類成員,數(shù)據(jù)屬性與函數(shù)組件的語句。

例子

下面是一個(gè)簡(jiǎn)單的Python類的例子:

            
class Employee:
  'Common base class for all employees'
  empCount = 0

  def __init__(self, name, salary):
   self.name = name
   self.salary = salary
   Employee.empCount += 1
  
  def displayCount(self):
   print "Total Employee %d" % Employee.empCount

  def displayEmployee(self):
   print "Name : ", self.name, ", Salary: ", self.salary


          

??? empCount是一個(gè)類變量,其值將是這個(gè)類的所有實(shí)例共享。這可以從類中或外部進(jìn)行訪問,訪問形式為 Employee.empCount。

??? 第一個(gè)方法__init__()是一種特殊的方法,這就是所謂的類構(gòu)造函數(shù)或當(dāng)創(chuàng)建該類的一個(gè)新實(shí)例Python調(diào)用的初始化方法。

??? 聲明就像正常函數(shù)中一樣,不同的是第一個(gè)參數(shù)到每個(gè)方法是類的方法。 Python增加了self參數(shù)列表;不需要把調(diào)用的方法都它列入。

創(chuàng)建實(shí)例對(duì)象:

要?jiǎng)?chuàng)建一個(gè)類的實(shí)例,調(diào)用類名并傳遞任何參數(shù)給__init__方法接收。

            
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)


          

訪問屬性:

可以訪問使用點(diǎn)運(yùn)算符來訪問對(duì)象的屬性。而類變量使用類名來訪問,如下所示:

            
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount


          

現(xiàn)在,把所有的概念放在一起:

            
#!/usr/bin/python

class Employee:
  'Common base class for all employees'
  empCount = 0

  def __init__(self, name, salary):
   self.name = name
   self.salary = salary
   Employee.empCount += 1
  
  def displayCount(self):
   print "Total Employee %d" % Employee.empCount

  def displayEmployee(self):
   print "Name : ", self.name, ", Salary: ", self.salary

"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount


          

當(dāng)執(zhí)行上面的代碼,產(chǎn)生以下結(jié)果:

            
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2


          

在任何時(shí)候可以添加,刪除或修改類和對(duì)象的屬性:

            
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.


          

除了使用正常的語句來訪問屬性,可以使用以下函數(shù):

  • ??? getattr(obj, name[, default]) : 訪問對(duì)象的屬性。
  • ??? hasattr(obj,name) : 檢查一個(gè)屬性是否存在。
  • ??? setattr(obj,name,value) : 設(shè)置一個(gè)屬性。如果屬性不存在,那么它將被創(chuàng)建。
  • ??? delattr(obj, name) : 要?jiǎng)h除一個(gè)屬性。
            
hasattr(emp1, 'age')  # Returns true if 'age' attribute exists
getattr(emp1, 'age')  # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age')  # Delete attribute 'age'


          

內(nèi)置的類屬性:

每個(gè)Python類會(huì)繼續(xù)并帶有內(nèi)置屬性,他們可以使用點(diǎn)運(yùn)算符像任何其他屬性一樣來訪問:

  • ??? __dict__ : 字典包含類的命名空間。
  • ??? __doc__ : 類的文檔字符串,或None如果沒有定義。
  • ??? __name__: 類名稱。
  • ??? __module__: 在類中定義的模塊名稱。此屬性是在交互模式其值為“__main__”。
  • ??? __bases__ : 一個(gè)可能是空的元組包含了基類,其在基類列表出現(xiàn)的順序。

對(duì)于上面的類,嘗試訪問這些屬性:

            
#!/usr/bin/python

class Employee:
  'Common base class for all employees'
  empCount = 0

  def __init__(self, name, salary):
   self.name = name
   self.salary = salary
   Employee.empCount += 1
  
  def displayCount(self):
   print "Total Employee %d" % Employee.empCount

  def displayEmployee(self):
   print "Name : ", self.name, ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__


          

當(dāng)執(zhí)行上面的代碼,產(chǎn)生以下結(jié)果:

            
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':

            
              , 'empCount': 2, 
'displayEmployee': 
              
                , 
'__doc__': 'Common base class for all employees', 
'__init__': 
                
                  }


                
              
            
          

銷毀對(duì)象(垃圾回收):

Python的刪除不需要的對(duì)象(內(nèi)建類型或類的實(shí)例),自動(dòng)釋放內(nèi)存空間。由Python定期回收的內(nèi)存塊不再使用的過程被稱為垃圾收集。

Python的垃圾回收器在程序執(zhí)行過程中運(yùn)行,當(dāng)一個(gè)對(duì)象的引用計(jì)數(shù)為零時(shí)觸發(fā)。一個(gè)對(duì)象的引用計(jì)數(shù)改變?yōu)橹赶蛩淖儎e名的數(shù)量。

當(dāng)它分配一個(gè)新的名字或放置在容器(列表,元組或字典)的對(duì)象的引用計(jì)數(shù)增加。當(dāng)對(duì)象的引用計(jì)數(shù)減少使用 del 刪除,其基準(zhǔn)被重新分配,或者它的引用超出范圍。當(dāng)一個(gè)對(duì)象的引用計(jì)數(shù)變?yōu)榱悖琍ython會(huì)自動(dòng)地收集它。

            
a = 40   # Create object <40>
b = a    # Increase ref. count of <40> 
c = [b]   # Increase ref. count of <40> 

del a    # Decrease ref. count of <40>
b = 100   # Decrease ref. count of <40> 
c[0] = -1  # Decrease ref. count of <40> 


          

當(dāng)垃圾回收器銷毀孤立的實(shí)例,并回收其空間一般不會(huì)注意到。但是,一個(gè)類可以實(shí)現(xiàn)特殊方法__del__(),稱為析構(gòu)函數(shù)被調(diào)用時(shí),該實(shí)例將被摧毀。這個(gè)方法可以用于清理所用的一個(gè)實(shí)例的任何非內(nèi)存資源。
例子:

__del__()析構(gòu)函數(shù)打印實(shí)例,它即將被銷毀的類名:

            
#!/usr/bin/python

class Point:
  def __init( self, x=0, y=0):
   self.x = x
   self.y = y
  def __del__(self):
   class_name = self.__class__.__name__
   print class_name, "destroyed"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3


          

當(dāng)執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果:

            
3083401324 3083401324 3083401324
Point destroyed 


          

注意:理想情況下,應(yīng)該定義類的單獨(dú)的文件,那么應(yīng)該使用import語句將其導(dǎo)入主程序文件。詳細(xì)請(qǐng)查看Python- 模塊章節(jié),導(dǎo)入模塊和類的更多細(xì)節(jié)。
類繼承:

不用從頭開始,可以通過上面列出的括號(hào)父類的新類名后,從一個(gè)已經(jīng)存在的類派生它創(chuàng)建一個(gè)類。

子類繼承父類的屬性,可以使用父類的這些屬性,就好像它們是在子類中定義的一樣。子類也可以覆蓋父類的數(shù)據(jù)成員和方法。
語法

派生類的聲明很像它們的父類; 從基類的列表后給出類名繼承:

            
class SubClassName (ParentClass1[, ParentClass2, ...]):
  'Optional class documentation string'
  class_suite


          

例子

            
#!/usr/bin/python

class Parent:    # define parent class
  parentAttr = 100
  def __init__(self):
   print "Calling parent constructor"

  def parentMethod(self):
   print 'Calling parent method'

  def setAttr(self, attr):
   Parent.parentAttr = attr

  def getAttr(self):
   print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class
  def __init__(self):
   print "Calling child constructor"

  def childMethod(self):
   print 'Calling child method'

c = Child()     # instance of child
c.childMethod()   # child calls its method
c.parentMethod()   # calls parent's method
c.setAttr(200)    # again call parent's method
c.getAttr()     # again call parent's method


          

當(dāng)執(zhí)行上面的代碼,產(chǎn)生以下結(jié)果:

            
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200


          

類似的方式,可以按如下繼承多個(gè)父類的類:

復(fù)制代碼 代碼如下:
class A:??????? # define your class A
.....

class B:???????? # define your calss B
.....

class C(A, B):?? # subclass of A and B
.....

可以使用issubclass()或isinstance()函數(shù)來檢查兩個(gè)類和實(shí)例的關(guān)系。

  • ??? issubclass(sub, sup) 如果給定的子類子確實(shí)是超sup的子類布爾函數(shù)返回true。
  • ??? isinstance(obj, Class) 如果obj是Class類的實(shí)例,或者是類的一個(gè)子類的實(shí)例布爾函數(shù)返回true

重寫方法:

可以覆蓋父類的方法。原因之一重寫父的方法,因?yàn)榭赡芟朐谧宇愄厥饣驅(qū)崿F(xiàn)不同的功能。
例子

            
#!/usr/bin/python

class Parent:    # define parent class
  def myMethod(self):
   print 'Calling parent method'

class Child(Parent): # define child class
  def myMethod(self):
   print 'Calling child method'

c = Child()     # instance of child
c.myMethod()     # child calls overridden method


          

當(dāng)執(zhí)行上面的代碼,產(chǎn)生以下結(jié)果:

            
Calling child method


          

基礎(chǔ)重載方法:

下表列出了一些通用的功能,可以在類重寫中:

深入講解Python中面向?qū)ο缶幊痰南嚓P(guān)知識(shí)_第1張圖片

?重載運(yùn)算符:

假設(shè)要?jiǎng)?chuàng)建了一個(gè)Vector類來表示二維向量,當(dāng)使用加運(yùn)算符來增加他們發(fā)生了什么?最有可能是Python會(huì)?拍恪?

可以,但是定義__add__方法在類中進(jìn)行矢量相加,再加上操作符的行為會(huì)按預(yù)期:
例子:

            
#!/usr/bin/python

class Vector:
  def __init__(self, a, b):
   self.a = a
   self.b = b

  def __str__(self):
   return 'Vector (%d, %d)' % (self.a, self.b)
  
  def __add__(self,other):
   return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2


          

當(dāng)執(zhí)行上面的代碼,產(chǎn)生以下結(jié)果:

            
Vector(7,8)


          

數(shù)據(jù)隱藏:

對(duì)象的屬性可以是或可以不在類定義外部可見。對(duì)于這些情況,可以命名以雙下劃線前綴屬性,這些屬性將無法直接讓外部可視。
例子:

            
#!/usr/bin/python

class JustCounter:
  __secretCount = 0
 
  def count(self):
   self.__secretCount += 1
   print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount


          

當(dāng)執(zhí)行上面的代碼,產(chǎn)生以下結(jié)果:

            
1
2
Traceback (most recent call last):
 File "test.py", line 12, in 
            
              
  print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'


            
          

Python的保護(hù)成員通過內(nèi)部更改名稱以包含類名。可以訪問這些屬性通過object._className__attrName。如果想更換最后一行,那么它會(huì)工作如下:

            
.........................
print counter._JustCounter__secretCount


          

當(dāng)執(zhí)行上面的代碼,產(chǎn)生以下結(jié)果:

            
1
2
2


          


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 天祝| 洪雅县| 遂平县| 临邑县| 隆化县| 成武县| 仁布县| 鲁甸县| 松潘县| 弥勒县| 抚州市| 丹东市| 南丹县| 福安市| 东乌珠穆沁旗| 陵水| 武鸣县| 维西| 北安市| 应用必备| 金溪县| 资兴市| 合江县| 凤山市| 余江县| 镇原县| 岳阳市| 库尔勒市| 黄浦区| 吴旗县| 濉溪县| 眉山市| 和平县| 武宣县| 屏南县| 赣州市| 余江县| 镇宁| 昭觉县| 库尔勒市| 彩票|