python 中物件導向編程簡單總結2

來源:互聯網
上載者:User

標籤:

1.python中繼承的特點:

  (1)總是從一個類繼承,預設為object類

  (2)不要忘記調用super.__init__方法來初始化父類的方法

def __init__(self,args):    super(Subclass,self).__init__(args)    pass

  簡單例子

class Person(object):    def __init__(self,name,gender):        self.name = name        self.gender = genderclass Student(Person):    def __init__(self,name,gender,score):        #super(Student,self)方法調用返回當前類繼承的父類        #如果沒有下面的調用,那麼Student類中就沒有name和gender屬性        super(Student,self).__init__(name,gender)        self.score = scores = Student("roger","male",99)print s.name,s.gender,s.score

2. 使用isinstance(obj,class)來判斷obj是否是class類的一個執行個體

3.繼承和多態需要注意的地方

  (1)python是動態語言,動態語言調用執行個體方法,不檢查類型,只要方法存在,參數正確,就可以調用。

  (2)如果執行個體中沒有相應的方法和屬性,那麼它會順著繼承鏈向上尋找。如果是方法,它就會調用最近的方法;如果是屬性,就會在執行個體上綁定一個屬性。

  (3)多態概念一致,任何能引用父類的地方,一定能使用子類

4.定義類對象之後擷取相關屬性

  (1)type(obj) 返回變數類型

  (2) dir(obj) 返回變數所有屬性

  (3)getattr(obj,attrname) 擷取屬性: attrname

  (4)setattr(obj,attrname,attrvalue): 設定新的屬性

  (5)Python 中的變長參數:*args(只含值), **kwargs(包含索引值對),注意到兩者調用上是有區別的。

#coding=utf8__author__ = ‘Administrator‘# 當函數的參數不確定時,可以使用*args和**kwargs。*args沒有key值,**kwargs有key值def fun_var_args(farg, *args):    print ‘args:‘, farg    for value in args:        print ‘another arg:‘,valuefun_var_args(1, ‘two‘, 3, None)
class Person(object):    def __init__(self, name, gender, **kw):        self.name = name        self.gender = gender        for k, v in kw.iteritems():            setattr(self, k, v)p = Person(‘Bob‘, ‘Male‘, age=18, course=‘Python‘)print p.ageprint p.course

 

python 中物件導向編程簡單總結2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.