前面提到的操作函數和語句塊是傳統的面向過程編程,而編寫大型程式,通常採用物件導向編程。類和對象是物件導向編程的兩個主要方面,類建立一個新類型,而對象是類的執行個體。Python沒有什麼實值型別與參考型別之分,它把所有事物統統看作是類。類使用class關鍵字來建立。
1. Self
類的方法與普通的函數只有一個特別的區別——它們必須有一個額外的第一個參數名稱,但是在調用這個方法的時候你不為這個參數賦值,Python會提供這個值。這個特別的變數指對象本身,按照慣例它的名稱是self。
你一定很奇怪Python如何給self賦值以及為何你不需要給它賦值。舉一個例子會使此變得清晰。假如你有一個類稱為MyClass和這個類的一個執行個體MyObject。當你調用這個對象的方法MyObject.method(arg1, arg2)的時候,這會由Python自動轉為MyClass.method(MyObject, arg1, arg2)——這就是self的原理了。
2. 類
一個空類:
class Person: pass #An empty block
類的使用:
p = Person()print(p)
3. 方法
類/對象可以擁有像函數一樣的方法,這些方法與函數的區別只是一個額外的self變數。
class Person: def sayHi(self): print("Hello, how are you?")p = Person()p.sayHi()
注意調用sayHi方法時沒有任何參數,但仍然在函數定義時有self。
4. __init__方法
在Python的類中有很多方法的名字有特殊的重要意義。像__init__,類似於建構函式。__init__方法在類的一個對象被建立時,馬上運行。這個方法可以用來對你的對象做一些你希望的初始化 。注意,這個名稱的開始和結尾都是雙底線。
class Person: def __init__(self, name): self.name = name def sayHi(self): print("Hello, my name is", self.name)p = Person("known")p.syaHi()
5. 域
Python有兩種類型的域——類的變數和對象的變數,它們根據是類還是對象擁有這個變數而區分。
類的變數由一個類的所有對象(執行個體)共用使用。只有一個類變數的拷貝,所以當某個對象對類的變數做了改動的時候,這個改動會反映到所有其他的執行個體上。
對象的變數由類的每個對象/執行個體擁有。因此每個對象有自己對這個域的一份拷貝,即它們不是共用的,在同一個類的不同執行個體中,雖然對象的變數有相同的名稱,但是是互不相關的。
class Person: '''Represnets a person.''' population = 0 def __init__(self, name): '''Initializes the person's data.''' self.name = name print("(Initializing %s)" % self.name) #When this person is created, he/she adds to the population Person.population += 1 def __del__(self): '''I am dying.''' print("%s says bye." % self.name) Person.population -= 1 if Person.population == 0: print("I am the last one.") else: print("There are still %d people left." % Person.population) def sayHi(self): '''Greeting by the person. Really, that's all it does.''' print("Hi, my name is %s." % self.name) def howMany(self): '''Prints the current population.''' if Person.population == 1: print("I am the only person here.") else: print("We have %d person here." % Person.population)swaroop = Person('Swaroop')swaroop.sayHi()swaroop.howMany()kalam = Person('Abdul Kalam')kalam.sayHi()kalam.howMany()swaroop.sayHi()swaroop.howMany()del kalamdel swaroop
運行結果:
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.
6. 繼承
在類名後面跟一對圓括弧,基類名寫在圓括弧內。
class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = name self.age = age print("(Initialized SchoolMember: %s)" % self.name) def tell(self): '''Tell my details.''' print("Name:'%s' Age:'%s'" % (self.name, self.age))class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print("(Initialized Teacher: %s)" % self.name) def tell(self): SchoolMember.tell(self) print("Salary: '%d'" % self.salary)class Student(SchoolMember): '''Represents a student.''' def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print("(Initialized Student: %s)" % self.name) def tell(self): SchoolMember.tell(self) print("Marks: '%d'" % self.marks)t = Teacher("Mrs. Shrividya", 40, 30000)s = Student("Swaroop", 22, 75)print() # prints a blank linemembers = [t, s]for member in members: member.tell() # works for both Teachers and Students
輸出結果:
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)
Name:'Mrs. Shrividya' Age:'40' Salary: '30000'
Name:'Swaroop' Age:'22' Marks: '75'