標籤:name amp 執行個體 pass nbsp form school ror blog
之前粗淺地學習過C++,對於物件導向有些瞭解,現在通過Python仔細學習一下物件導向:
類
類使用 class 關鍵字建立。類的域和方法被列在一個縮排塊中。
class Person: pass #pass語句表示一個空類p = Person()print(p)$ python simplestclass.py<__main__.Person object at 0x019F85F0>
#我們已經在 __main__ 模組中有了一個 Person 類的執行個體
對象的方法
class Person: def sayHi(self): #定義函數的時候有self print(‘Hello, how are you?‘)p = Person()p.sayHi()# This short example can also be written as Person().sayHi()
__init__方法
這個名稱的開始和結尾都是雙底線
(感覺就像C++中的建構函式)
class Person: def __init__(self, name): self.name = name def sayHi(self): print(‘Hello, my name is‘, self.name) p = Person(‘Swaroop‘)
一個對象創立時,該函數馬上運行。
類和物件變數
就像C++中的靜態變數和執行個體變數一樣,很好理解,直接看這我寫的簡單的一個例子:
#Filename:claaOrInsVarclass animal: population = 0 def __init__(self,name): self.name = name animal.population += 1 def sayHi(self): print("My name is " + self.name) def howMany ( ): #這個函數沒有傳遞參數self # print(‘We have ‘ + animal.population + ‘animals‘) #使用上面的代碼後程式報錯“ print(‘We have ‘ + animal.population + ‘animals‘) #TypeError: must be str, not int” #animal.population 無法自動和字串進行串連,java中是可以有運算式的自動提升的,python中卻不能這樣做 print(‘We have {0} animals.‘.format(animal.population))an1 = animal(‘dogWW‘)an1.sayHi()an2 = animal(‘catMM‘)an2.sayHi()animal.howMany()繼承
class SchoolMenber: def __init__(self,name,age): self.name = name self.age = age def tell(self): print(‘name:{0} age:{1}‘.format(self.name,self.age))class Teacher(SchoolMenber): def __init__(self,name,age,salary): SchoolMenber.__init__(self,name,age)#這裡的self不要忘了寫啊 self.salary = salary def tell(self): SchoolMenber.tell(self) print(‘salary: {0}‘.format(self.salary))class Student(SchoolMenber): def __init__(self,name,age,mark): SchoolMenber.__init__(self,name,age) self.mark = mark def tell(self): SchoolMenber.tell(self) print(‘mark:{0}‘.format(self.mark))stu = Student(‘Jenny‘,20,95)tec = Teacher(‘Mary‘,50,5000)menbers = [stu,tec]for menber in menbers: menber.tell()
開始學習Python物件導向編程