python的繼承:
class derivedclassname(baseclassname):
......
當出現子類想要在父類的某一方法的基礎上增添功能的話,可以採用下面的技術實現:
①呼叫未繫結的父類方法
②使用super()函式。在多重繼承時,不用給定任何基類的名字,會自動一層層找出所有基類對應的方法。當想改變類的繼承關係的時候只需要修改()裡類的名字就可以了,而不用再去改super()的內容。
import random
class fish:
def __init__(self):
self.x = random.randint(0, 10)
self.y = random.randint(0, 10)
def move(self):
self.x -= 1
print("我的位置是:", self.x, self.y)
class goldfish(fish):
pass
class sharp(fish):
def __init__(self):
#解決方法①fish.__init__(self) 裡面的self是子類的例項物件
#解決方法②super().__init__() super().需要父類的方法,會自動傳入物件引數
self.hungry = true
def eat(self):
if self.hungry:
print("吃吃吃")
self.hungry = false
else:
print("飽了")
>>> goldfish = goldfish()
>>> goldfish.move()
我的位置是: 1 6
>>> sharp = sharp()
>>> sharp.eat()
吃吃吃》 sharp.move() #呼叫move()方法出錯,原因是sharp子類覆蓋了父類的建構函式,導致沒有定義x變數
traceback (most recent call last):
file "", line 1, in sharp.move()
file "e:/1程式/python/類與物件.py", line 9, in move
self.x -= 1
attributeerror: 'sharp' object has no attribute 'x'
python也支援多重繼承
多重繼承:
class derivedclassname(base1, base2, base3):
......
組合:把類的例項化放到新類中
class tutle:
def __init__(self, x):
self.num = x
class pool:
def __init__(self, x):
self.tutle = tutle(x) #組合
def print_num(self):
print('池塘裡有烏龜%d只' % self.tutle.num)
魚c筆記 Python物件導向程式設計
ooa 物件導向分析 oop 物件導向程式設計 ood 物件導向設計 關於self python的self相當於c 的this指標。由同乙個類可以生成無數的物件,當乙個物件的方法被呼叫的時候,物件會將自身作為第乙個引數傳遞給self引數,接受到這個self引數時,python就知道是哪個物件在呼叫方...
Python 類與物件筆記
類與物件 python 類的語法 關鍵字class def函式名 引數 函式關鍵字 class 類名 類名的規範是數字字母下劃線 不能以數字開頭 首字母大寫 駝峰命名 類屬性類方法 class boyfriend 類屬性 height 175 weight 130 money 500萬 類函式 類方...
Python學習筆記 類與物件
基於python3版本的學習。生活中我們所說的類,是物以類聚的類,是分門別類的類,是多個類似事物組成的群體的統稱。而在python中我們所遇到的類 class 比如整數 字串 浮點數等,不同的資料型別就屬於不同的類。準確來說,它們的全名是整數類 字串類 浮點數類。每乙個類之下都包含無數相似的不同個例...