在面向對象的世界里,
你的代碼通常稱為類的方法
method
,
而數據通常稱為類的屬性
attribute
,
實例化的數據對象通常稱為實例
instance
。
Python使用class
創建類。每個定義的類都有一個特殊的方法,名為__init__()
,可以通過這個方法控制如何初始化對象。
類中方法的定義與函數的定義類似,基本形式如下:
class Athlete:
def __init__(self):
# The code to initialize a "Athlete" object.
1. __init__()方法
有了類之后,創建對象實例很容易。只需將對類名的調用賦至各個變量。通過這種方式,類(以及__init__()
方法)提供了一種機制,允許你創建一個定制的工廠函數,用來根據需要創建多個對象實例。
與C++系列語言不同,Python中沒有定義構造函數new
的概念。Python會對你完成對象構建,然后你可以使用__init__()
方法定制對象的初始狀態。
2. self參數
Python處理實例化a = Athlete()
時,把工廠函數調用轉換為了Athlete().__init__(a)
,也就是說,Python會將實例的目標標識符a
賦至self
參數中,這是一個非常重要的參數賦值。如果沒有這個賦值,Python解釋器無法得出方法調用要應用到哪個對象實例。
注意:
類代碼設計為在所有對象實例間共享:方法是共享的,而屬性不共享。self
參數可以幫助標識要處理哪個對象實例的數據。
每一個方法的第一個參數都是self
。
class Athlete:
def __init__(self, a_name, a_dob=None, a_times=[]):
self.name = a_name
self.dob = a_dob
self.times = a_times
def top3(self):
return(sorted(set([sanitize(t) for t in self.times])) [0:3])
def add_time(self, time_value):
self.times.append(time_value)
def add_times(self, list_of_times):
self.times.extend(list_of_times)
3. 繼承
可以繼承list類創建AthleteList類,list類自帶append()
和extend()
方法
class AthleteList(list):
def __init__(self, a_name, a_dob=None, a_times=[]):
list.__init__([])
self.name = a_name
self.dob = a_dob
self.extend(a_times)
def top3(self):
return (sorted(set([sanitize(t) for t in self])) [0:3])
4. 代碼示例
def sanitize(time_string):
if '_' in time_string:
splitter = '_'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins, secs) = time_string.split(splitter)
return(mins + '.' + secs)
class AthleteList(list):
def __init__(self, a_name, a_dob=None, a_times=[]):
list.__init__([])
self.name = a_name
self.dob = a_dob
self.extend(a_times)
def top3(self):
return (sorted(set([sanitize(t) for t in self])) [0:3])
def get_coach_data(filename):
try:
with open(filename) as f:
data = f.readline()
templ = data.strip().split(',')
return (Athlete(templ.pop(0), templ.pop(0), templ))
except IOError as ioerr:
print('File error: ', + str(ioerr))
return(None)
james = get_coach_data('james2.txt')
print(james.name + "'s fastest times are: " + str(james.top3()))