Python定義一個類

在面向?qū)ο蟮氖澜缋铮?br> 你的代碼通常稱為 類的方法 method,
而數(shù)據(jù)通常稱為 類的屬性 attribute
實例化的數(shù)據(jù)對象通常稱為 實例 instance。

Python使用class創(chuàng)建類。每個定義的類都有一個特殊的方法,名為__init__(),可以通過這個方法控制如何初始化對象。
類中方法的定義與函數(shù)的定義類似,基本形式如下:

class Athlete:
    def __init__(self):
        # The code to initialize a "Athlete" object.

1. __init__()方法

有了類之后,創(chuàng)建對象實例很容易。只需將對類名的調(diào)用賦至各個變量。通過這種方式,類(以及__init__()方法)提供了一種機制,允許你創(chuàng)建一個定制的工廠函數(shù),用來根據(jù)需要創(chuàng)建多個對象實例。
與C++系列語言不同,Python中沒有定義構(gòu)造函數(shù)new的概念。Python會對你完成對象構(gòu)建,然后你可以使用__init__()方法定制對象的初始狀態(tài)。

2. self參數(shù)

Python處理實例化a = Athlete()時,把工廠函數(shù)調(diào)用轉(zhuǎn)換為了Athlete().__init__(a),也就是說,Python會將實例的目標標識符a賦至self參數(shù)中,這是一個非常重要的參數(shù)賦值。如果沒有這個賦值,Python解釋器無法得出方法調(diào)用要應(yīng)用到哪個對象實例。
注意:類代碼設(shè)計為在所有對象實例間共享:方法是共享的,而屬性不共享。self參數(shù)可以幫助標識要處理哪個對象實例的數(shù)據(jù)。
每一個方法的第一個參數(shù)都是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. 繼承

可以繼承l(wèi)ist類創(chuàng)建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()))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容