Python 類的特殊成員介紹

來源:互聯網
上載者:User

標籤:對象   派生   私人   stat   int   相加   特殊成員   python   str   

類的成員有兩種形式

公有成員,在任何地方都能訪問
私人成員,只有在類的內部才能方法,私人成員命名時,前兩個字元是底線。

class Foo:    def __init__(self, name, age):        self.name = name        self.__age = age    def show(self):            # 間接方法私人欄位        return self.__age    obj = Foo(‘klvchen‘, 25)print(obj.name)res = obj.show()print(res)運行結果:klvchen25

公有靜態欄位:類可以訪問;類內部可以訪問;衍生類別中可以訪問
私人靜態欄位:僅類內部可以訪問;

class Foo:    __v = ‘666‘         # 私人靜態欄位    def __init__(self):        pass    def show(self):        return Foo.__vobj = Foo()res = obj.show()print(res)運行結果:666
class Foo:    __v = ‘666‘    def __init__(self):        pass    def show(self):        return Foo.__v    @staticmethod    def stat():        return Foo.__vres = Foo.stat()print(res)運行結果:666
無法從父類繼承私人欄位
class F:    def __init__(self):        self.ge = 123        self.__gene = 456     #私人欄位class S(F):    def __init__(self, name):        self.name = name        self.__age = 18        super(S, self).__init__()    def show(self):        print(self.name)        print(self.__age)        print(self.ge)        print(self.__gene)s = S(‘klvchen‘)s.show()運行結果:klvchen18123AttributeError: ‘S‘ object has no attribute ‘_S__gene‘
類的特殊成員int(對象),會自動執行對象中的__int__方法,並將返回賦值給 int 對象,同理 str(對象),會自動執行__str__方法,並返回賦值給 str 對象。
class Foo:    def __init__(self):        pass    def __int__(self):        return 666    def __str__(self):        return ‘hello world‘obj = Foo()print(obj, type(obj))res = int(obj)print(res)res1 = str(obj)print(res1)運行結果:<__main__.Foo object at 0x0000022BBE9DA978> <class ‘__main__.Foo‘>666hello world
print(對象),str(對象),都會自動執行對象中的__str__方法,並返回
class Foo:    def __init__(self, n, a):        self.name = n        self.age = a    def __str__(self):        return ‘%s-%d‘ %(self.name, self.age)obj = Foo(‘klvchen‘, 28)print(obj)運行結果:klvchen-28
兩個對象相加時,自動執行第一對象的__add__方法,並且將第二個對象當參數傳遞進去
class Foo:    def __init__(self, name, age):        self.name = name        self.age = age    def __add__(self, other):        return self.age + other.ageobj1 = Foo(‘klv1‘, 23)obj2 = Foo(‘klv2‘, 24)res = obj1 +  obj2print(res, type(res))運行結果:47 <class ‘int‘>
class Foo:    def __init__(self, name, age):        self.name = name        self.age = age    def __add__(self, other):        return Foo(obj1.name, obj2.age)    def __del__(self):        print(‘析構方法‘)obj1 = Foo(‘klv1‘, 23)obj2 = Foo(‘klv2‘, 24)res = obj1 + obj2print(res, type(res))運行結果:<__main__.Foo object at 0x0000016DFCE125C0> <class ‘__main__.Foo‘>析構方法析構方法析構方法
li[對象] 會自動執行 li 對象的類中的__getitem__方法,8當作參數傳遞給item
class Foo:    def __init__(self, name, age):        self.name = name        self.age = age    def __getitem__(self, item):        return itemli = Foo(‘klvchen‘, 28)r = li[8]print(r)運行結果:8
類中的__setitem__,__delitem__方法
class Foo:    def __init__(self, name, age):        self.name = name        self.age = age    def __getitem__(self, item):        return item    def __setitem__(self, key, value):        print(key, value)    def __delitem__(self, key):        print(key)li = Foo(‘klvchen‘, 28)r = li[8]print(r)li[100] = ‘hello‘del li[999]運行結果:8100 hello999
執行類中的__iter__()方法,並擷取其傳回值,迴圈上一步中返回對象,用於迭代器,之所以列表、字典、元組可以進行for迴圈,是因為類型內部定義了 iter
class Foo:    def __init__(self, name, age):        self.name = name        self.age = age    def __iter__(self):        return iter([11, 22, 33])li = Foo(‘klvchen‘, 26)for i in li:    print(i)運行結果:112233

for 迴圈的內部操作

obj = iter([11, 22, 33])while True:    val = obj.next()    print val

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.