Python 物件導向編程基礎——初始化執行個體、類屬性、方法

來源:互聯網
上載者:User

標籤:返回   elf   job   ret   需要   tom   調用   cti   span   

#1.初始化執行個體化屬性。
#可接受任意關鍵字參數,並把他們都作為屬性賦值給執行個體。使用**kw,除了可以直接使用self.name = ‘xxx‘設定一個屬性外,還可以通過setattr(self, ‘name‘, ‘xxx‘)設定屬性。
class Person(object):
    def __init__(self, name, gender, **kw):
        self.name = name
        self.gender = gender
        for k,v in kw.items():
            setattr(self, k, v)
           
xiaoming = Person(‘Xiao Ming‘, ‘Male‘, birth=‘1990-1-1‘, job=‘Student‘)
print(xiaoming.name)
print(xiaoming.job)

#2.類中的私人成員,雙底線開頭的"__score"不能直接被外部存取。
class Person1(object):
    def __init__(self, name, score):
        self.name = name
        self._gender = ‘Male‘
        self.__score = score
p1 = Person1(‘Bob‘, 59)
try:
    print(p1.__score)  #AttributeError: ‘Person1‘ object has no attribute ‘__score‘
except AttributeError:
    print(‘attrbuteerror‘)

#3.建立類屬性。執行個體屬性每個執行個體都各自擁有,互相獨立,而類屬性有且只有一份。
class Person2(object):
    address = ‘Earth‘
    def __init__(self, name):
        self.name = name
print(Person2.address)
p2 = Person2(‘Tom‘)
print(Person2.address)
#請給Person3類添加一個類屬性count每建立一個執行個體count屬性就加1這樣就可以統計出一共建立了多少個Person3的執行個體。
class Person3(object):
    count = 0
    def __init__(self, name):
        self.name = name
        Person3.count += 1
p3 = Person3(‘Alice‘)
print(p3.count)
p3_1 = Person3(‘Tim‘)
print(p3_1.count)

#4.python中類屬性和執行個體屬性名稱字衝突怎麼辦?
#請把上節的Person3類屬性count改為__count,再試試能否從執行個體和類訪問該屬性。
class Person4(object):
    __count = 0
    def __init__(self, name):
        self.name = name
        Person4.__count += 1
        print(Person4.__count)
p4 = Person4(‘Bob‘)
p4_1 = Person4(‘Alice‘)
try:
    print(Person4.__count)  #AttributeError: type object ‘Person4‘ has no attribute ‘__count‘
except AttributeError:
    print(‘AttributeError‘)
##類屬性的公開和私人,如果沒有雙底線,外部可以調用,如果有,只能在類內部使用。

#5.一個執行個體的私人屬性就是以__開頭的屬性,無法被外部存取,那這些屬性定義有什麼用?
#雖然私人屬性無法從外部存取,但是,從類的內部是可以訪問的。除了可以定義執行個體的屬性外,還可以定義執行個體的方法。
#執行個體的方法就是在類中定義的函數,它的第一個參數永遠是self,指向調用該方法的執行個體本身,其他參數和一個普通函數是完全一樣的:
class Person5(object):
    def __init__(self, name):
        self.__name = name
    def get_name(self):
        return self.__name
p5 = Person5(‘Bob‘)
print(p5.get_name())
#任務:請給Person5類增加一個私人屬性__score,表示分數,再增加一個執行個體方法get_grade(),
#能根據__score的值分別返回A-優秀, B-及格, C-不及格三檔。
class Person6(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score
    def get_grade(self):
        if self.__score >= 80:
            return "A-Excellent"
        elif self.__score >= 60:
            return "B-Passed"
        return "C-Failed"
p6_1 = Person6(‘Bob‘, 89)
p6_2 = Person6(‘Alice‘, 69)
p6_3 = Person6(‘Tim‘, 59)
print(p6_1.get_grade())
print(p6_2.get_grade())
print(p6_3.get_grade())

#6.python中方法也是屬性,由於屬性可以是普通的值對象,如str,int等,也可以是方法,還可以是函數,大家看看下面代碼的運行結果,請想一想p6.get_grade為什麼是函數而不是方法:
class Person6(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score
        self.get_grade = lambda: ‘A‘
p6 = Person6(‘Bob‘, 90)
print(p6.get_grade)    #<function Person6.__init__.<locals>.<lambda> at 0x000001D1244300D0>
print(p6.get_grade())  #A
#直接把lambda函數賦值給self.get_grade和Binder 方法有所不同,函數調用不需要傳入self,但是方法調用需要傳入self。
#p6.get_grade是屬性,只不過這裡的屬性是一個函數對象.
#p6.get_grade()是方法,前面的p6就是調用這個方法的對象,即執行個體,整句來說就是執行個體方法

 

Python 物件導向編程基礎——初始化執行個體、類屬性、方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.