本節課主要講述了class,object,method這些概念。
1.首先講述了python中的任何一個數據類型都是一個類。任何一個數據,都是類的一個實體。類的作用能夠更好地抽象所描述的對象,將相關的數據和方法封裝起來。對於相似功能的方法,因爲屬於不同的類,可以有同樣的命名,但是功能卻更適合所屬的類。
2.其次舉例說明了類,對象,方法的定義,實現和使用的方法。這裏舉了一個Fraction類的編寫過程的例子。
本篇筆記和代碼都來自於MIT的公開課,第八課,面向對象編程。《Introduction to Computer Science and Programming in Python》。
什麼是對象
Python中的每一種數據類型都是一個對象,比如int,float,string,list,dict。都是一個對象。每個對象都有
- 一種類型
- 一種數據表示方法
- 一些方法,用於交互
簡單例子
一個常見的類,list。
x_list = ['Peggy','Susie','Daniel']
list是一個類(class),x_list是對象(object),也可以說是類的一個實例(instance)。在list這個類裏面,定義了 +, *, append(),pop() 等等方法(method)。
編寫一個類
任務:編寫一個類,Fraction。
要求:
- 輸入是分子和分母,都是整型。
- 可以做分數加減法和倒數運算。
- 輸出有分數形式和小數形式。
步驟:
1.寫class的定義,定義的格式如下
class 關鍵字 class的名稱 (class的父類)
class Fraction(object):
object意味着Fraction是一個python對象,並且繼承了object的所有attribute。
object是Fraction的一個超集,而Fraction是object的一個子集。
2._init_()方法,接受輸入參數,賦值給class的類型。賦值之前先判斷輸入是否爲整型。所有在該類型下使用的instance variable,都必須在__init__()方法類定義,最好不要在其他方法內隨意寫self.variable,以免在繼承時發生錯誤。初始化時將沒有傳入參數的變量設置爲默認值或者爲空。
def __init__(self, num, denom):
""" num and denom are integers """
assert type(num) == int and type(denom) == int, "ints not used"
self.num = num
self.denom = denom
3._str_()方法,用來定義使用print(object)的輸出格式。如果沒有定義,則打印結果會是 xx object at xx address。
def __str__(self):
""" Retunrs a string representation of self """
return str(self.num) + "/" + str(self.denom)
4._add_(),_sub_(),和_float_()方法,分別對應操作符 +,- 和float()方法。
def __add__(self, other):
""" Returns a new fraction representing the addition """
top = self.num*other.denom + self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
5.inverse()方法,用來求倒數。
def inverse(self):
""" Returns a new fraction representing 1/self """
return Fraction(self.denom, self.num)
編寫完成,就可以定義Fraction的對象,然後完成相應的操作和運算。
方法有兩類,一類是像 _init_(),前後各有兩個下劃線的,他們對應特定的操作符。這種方法使用時可以直接使用method(object),也可以class.methed(object).比如下方例子print(float©) 和 print(Fraction._float_©)。這類方法是python預先保留的。
另一類是inverse(),格式只能爲object.method()。這種方式強調了inverse()是屬於Fraction 類的一個method。這類方法是用戶定義的。在類的定義過程中,一個成員方法可以直接引用類的其他成員方法,引用方法爲 class.method(self, variables),記住一定要寫self。
以上代碼的運行結果如下
a = Fraction(1,4)
b = Fraction(3,4)
c = a + b # c is a Fraction object
print(c)
print(float(c))
print(Fraction.__float__(c))
print(float(b.inverse()))
##c = Fraction(3.14, 2.7) # assertion error
##print a*b # error, did not define how to multiply two Fraction objects
16/16
1.0
1.0
1.3333333333333333
以下是一些簡單的出錯信息解釋。
c = Fraction(3.14, 2.7)
#assertion error,__init__()要求輸入必須是整型。
print a*b
#error, did not define how to multiply two Fraction objects,沒有定義兩個Fraction object如何相乘
len(a)
#object of type 'Fraction' has no len()。Fraction類中沒有定義len()。
完整代碼如下,版權歸MIT 公開課MIT的公開課《Introduction to Computer Science and Programming in Python》所有。
#################
## EXAMPLE: simple class to represent fractions
## Try adding more built-in operations like multiply, divide
### Try adding a reduce method to reduce the fraction (use gcd)
#################
class Fraction(object):
"""
A number represented as a fraction
"""
def __init__(self, num, denom):
""" num and denom are integers """
assert type(num) == int and type(denom) == int, "ints not used"
self.num = num
self.denom = denom
def __str__(self):
""" Retunrs a string representation of self """
return str(self.num) + "/" + str(self.denom)
def __add__(self, other):
""" Returns a new fraction representing the addition """
top = self.num*other.denom + self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
def __sub__(self, other):
""" Returns a new fraction representing the subtraction """
top = self.num*other.denom - self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
def __float__(self):
""" Returns a float value of the fraction """
return self.num/self.denom
def inverse(self):
""" Returns a new fraction representing 1/self """
return Fraction(self.denom, self.num)