python的類與子類

[TOC]

1、類的定義
類是用來將代碼與代碼處理的數(shù)據(jù)相關(guān)聯(lián),有助于降低復(fù)雜性,更易維護(hù)代碼;
python也提供了一種方法將代碼及其處理的數(shù)據(jù)定義為一個類,一旦有了類,就可以用它來創(chuàng)建(或?qū)嵗?shù)據(jù)對象,它會繼承類的特性;
在面向?qū)ο蟮氖澜缋?,代碼通常稱為類的方法method,而數(shù)據(jù)通常稱為類的屬性attribute,實例化的數(shù)據(jù)對象通常稱為實例instance。
每個對象都由類創(chuàng)建,并共享一組類似的特性。
定義一個類時,實際上是在定義一個定制工廠函數(shù),可以在代碼中引用這個函數(shù)

image.png

2、定義類及使用
Step1:使用class創(chuàng)建對象

class Athlete:                        #Athlete為類名
    def __init__(self):
    # the code to initialize a 'Athlete' object

Step2:創(chuàng)建對象實例
將對類名的調(diào)用賦至各個變量,通過這種方式,類(以及init())方法提供了一種機(jī)制,允許創(chuàng)建一個定制的工廠函數(shù),用來根據(jù)需要創(chuàng)建多個對象實例:
a = Athlete()
b = Athlete()
c = Athlete()
d = Athlete()

image.png

3、self參數(shù)的重要性
是一個方法參數(shù),總是指向當(dāng)前對象實例

  • 目標(biāo)標(biāo)識符賦至self參數(shù)
  • 每個方法的第一個參數(shù)都是self

4、例子

class Athlete:
    def __init__(self,value = 0):
        self.thing = value
    def how_big(self):
        return(len(self.thing))

>>> d=Athlete("hello")
>>> d.how_big()
5
>>> d
<__main__.Athlete object at 0x03269FB0>
image.png
class Athlete:
    def __init__(self,a_name,a_dob=None,a_times=[]):
        self.name = a_name
        self.dob = a_dob
        self.times = a_times

>>> d =Athlete('q','2012-6-17',['2.36','2.35'])
>>> b =Athlete('p')
>>> type(d)
<class '__main__.Athlete'>
>>> type(b)
<class '__main__.Athlete'>
#雖然都由d和b都經(jīng)過了Athlete這個工廠函數(shù)處理,但是存儲在不同的內(nèi)存地址上

>>> d
<__main__.Athlete object at 0x02F09F90>
>>> b
<__main__.Athlete object at 0x0336F850>
>>> d.name
'q'
>>> d.dob
'2012-6-17'
>>> d.times
['2.36', '2.35']
>>> b.dob
>>> b.times
[]

子類

1、子類的定義
通過繼承現(xiàn)有的其他類來創(chuàng)建一個類,包括用list,set,dict提供的python內(nèi)置數(shù)據(jù)結(jié)構(gòu)類。

2、定義子類及使用

  • NamedList:新類名
  • list:被派生的老類
  • list.init([]):初始化所派生的類
  • self.name = a_name:把參數(shù)賦至屬性
>>> class NamedList(list):
    def __init__(self,a_name):
        list.__init__([])
        self.name = a_name

        
>>> j = NamedList("Jone")
>>> type(j)
<class '__main__.NamedList'>
>>> dir(j)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'name', 'pop', 'remove', 'reverse', 'sort']
>>> j.append('b')
>>> j
['b']
>>> j.name
'Jone'
?著作權(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)容