開始學習Python物件導向編程

來源:互聯網
上載者:User

標籤: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物件導向編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.