標籤:種類 bin 類的屬性 調用 並且 err second arm ase
1. 類的建立
類是一種資料結構,我們可以用它來定義對象,後者把資料值和行為特性融合在一起。類是現實世界的抽象的實體以編程形式出現。執行個體是這些對象的具體化。
類名通常由大寫字母打頭。這是標準慣例
class First(): passif __name__ == ‘__main__‘: f = First() f.x = 3 f.y = 5 print(f.x + f.y )
2. 方法
self 參數,它在所有的方法聲明中都存在。這個參數代表執行個體對象本身,當你用執行個體調用方法時,由解譯器悄悄地傳遞給方法的,所以,你不需要自己傳遞 self 進來,因為它是自動傳入的。
調用一個方法的最終途徑
(a)定義類(和方法)
(b)建立一個執行個體
(c)最後一步,用這個執行個體調用方法。
class First(): def raiseup(self): print("raise it up!")if __name__ == ‘__main__‘: f = First() f.x = 3 f.y = 5 print(f.x + f.y ) f.raiseup()
通過類名直接調用方法First.raiseup()
D:\Python\Python35\python.exe D:/PycharmProjects/pythonOO/ff2.pyTraceback (most recent call last): File "D:/PycharmProjects/pythonOO/ff2.py", line 7, in <module> First.raiseup()TypeError: raiseup() missing 1 required positional argument: ‘self‘Process finished with exit code 1
綁定:
為與 OOP 慣例保持一致, Python 嚴格要求, 沒有執行個體, 方法是不能被調用的。 這種限制即 Python所描述的綁定概念(binding),在此,方法必須綁定(到一個執行個體) 才能直接被調用。非綁定的方法可能可以被調用,但執行個體對象一定要明確給出,才能確保調用成功。然而,不管是否綁定,方法都是它所在的類的固有屬性,即使它們幾乎總是通過執行個體來調用的。
3. __init__()
Python 建立執行個體後,在執行個體化過程中,調用__init__()方法,當一個類被執行個體化時,就可以定義額外的行為, 比如, 設定初始值或者運行一些初步診斷代碼———主要是在執行個體被建立後,執行個體化調用返回這個執行個體之前,去執行某些特定的任務或設定。 最後一句暫不明白
當對象 f被執行個體化後,它的f.name 就被設定了。
class First():
def __init__(self,name):
self.name = name
print("HI! " + self.name + "! Be prepared for raising it up!")
def raiseup(self):
print("raise it up!")
if __name__ == ‘__main__‘:
f = First(‘Alex‘)
f.raiseup()
運行
D:\Python\Python35\python.exe D:/PycharmProjects/pythonOO/first.pyHI! Alex! Be prepared for raising it up!raise it up!Process finished with exit code 0
4. 繼承
Python 中,當一個類被派生出來,子類繼承了基類的屬性,所以,在上面的類中,我們不僅定義了__init__(),updatEmail()方法,而且Second還從 First中繼承了 raiseup()方法。
如果需要,每個子類最好定義它自己的構造器,不然,基類的構造器會被調用。然而,如果子類重寫基類的構造器,基類的構造器就不會被自動調用了--這樣,基類的構造器就必須顯式寫出才會被執行,例如First.__init__(self,name)
這裡我們要顯式傳遞 self 執行個體對象給基類構造器,因為我們不是在其執行個體中調用那個方法而是在一個子類執行個體中調用那個方法。因為我們不是通過執行個體來調用它,這種未綁定的方法調用需要傳遞一個適當的執行個體(self)給方法。
class First(): def __init__(self,name): self.name = name print("HI! " + self.name + "! Be prepared for raising it up!") def raiseup(self): print("raise it up!")class Second(First): def __init__(self,name,weapon): First.__init__(self,name) self.weapon = weapon print("HI! " + self.name + "! Be prepared for raising it up! with " + self.weapon ) def raiseupWith(self): print("raise it up! with" + self.weapon)if __name__ == ‘__main__‘: s = Second(‘Alex‘,‘Python‘) s.raiseup() s.raiseupWith()
運行
D:\Python\Python35\python.exe D:/PycharmProjects/pythonOO/first.pyHI! Alex! Be prepared for raising it up!HI! Alex! Be prepared for raising it up! with Pythonraise it up!raise it up! withPythonProcess finished with exit code 0
如果不重新子類的__init__,執行個體化時,可使用父類的__init__
class First(): def __init__(self,name): self.name = name print("HI! " + self.name + "! Be prepared for raising it up!") def raiseup(self): print("raise it up!")class Second(First): def raiseupWith(self): print("raise it up! with" + self.weapon)if __name__ == ‘__main__‘: # s = Second(‘Alex‘,‘Python‘) s = Second(‘Alex‘) s.raiseup() s.raiseupWith()
D:\Python\Python35\python.exe D:/PycharmProjects/pythonOO/first.py
HI! Alex! Be prepared for raising it up!
Traceback (most recent call last):
raise it up!
File "D:/PycharmProjects/pythonOO/first.py", line 25, in <module>
s.raiseupWith()
File "D:/PycharmProjects/pythonOO/first.py", line 18, in raiseupWith
print("raise it up! with" + self.weapon)
AttributeError: ‘Second‘ object has no attribute ‘weapon‘
Process finished with exit code 1
5. 屬性
類的資料屬性
資料屬性僅僅是所定義的類的變數。它們可以像任何其它變數一樣在類建立後被使用,並且,要麼是由類中的方法來更新,要麼是在主程式其它什麼地方被更新。
即靜態變數,或者是待用資料。它們表示這些資料是與它們所屬的類對象綁定的,不依賴於任何類執行個體。如果你是一位 Java 或 C++程式員,這種類型的資料相當於在一個變數聲明前加上 static 關鍵字。
靜態成員通常僅用來跟蹤與類相關的值。
class Attri(): arrtitest = "class attribute test"if __name__ == ‘__main__‘: print(Attri.arrtitest)D:\Python\Python35\python.exe D:/PycharmProjects/pythonOO/class_attribute.pyclass attribute testProcess finished with exit code 0
查看類的屬性
print(dir(Second))[‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘,
‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__lt__‘, ‘__module__‘, ‘__ne__‘,
‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘,
‘__subclasshook__‘, ‘__weakref__‘, ‘raiseup‘, ‘raiseupWith‘]print(Second.__dict__){‘raiseupWith‘: <function Second.raiseupWith at 0x0000015AEFE46598>,
‘__module__‘: ‘__main__‘, ‘__doc__‘: None, ‘__init__‘: <function Second.__init__ at 0x0000015AEFE46510>}
特殊的類屬性
print(Second.__name__)Secondprint(Second.__base__)<class ‘__main__.First‘>print(Second.__module__)__main__print(Second.__class__)<class ‘type‘>
【python】python 物件導向編程筆記