Python,python基礎教程

來源:互聯網
上載者:User

Python,python基礎教程

Records學習筆記

                                      Records連結地址

1. __getitem__(self, key) 內建方法(Build-in)

例子:

 1 class Test(object): 2  3     def __getitem__(self, key): 4  5         print("test") 6  7         return 1 8  9 10 11 t = Test()12 13 print(t["m"])

 

運行結果:

>>> hello>>> 1

  

 

2. ___getattr__(self, name) 內建方法(Build-in)

該方法在未找到對象的屬性值的時候調用.

例子:

1 class Test(object):2     def __getattr__(self, name):3         print("test")4         return 15 6 t = Test()7 print(t.m)

運行結果:

>>> hello>>> 1

 

去掉__getattr__函數時,會提示沒有m這個屬性的錯誤。

 

3. @property 裝飾器

用於將一個函數生產對應的getter函數

執行個體:

class Test(object):    @property    def name(self):        return self._name    @name.setter    def name(self, name):        self._name = namet = Test()t.name = "hello"print(t.name)

運行結果:

>>> hello

 

4. A if 條件 else B(文法)

print("1") if __name__=='__main__' else print("2")

 

5. __enter__和__exit__內建方法(Build-in)

用於with語句塊,當進入with語句塊的時候調用__enter__

當離開with語句塊的時候調用__exit__

例子:

 1 class test(object): 2     def __enter__(self): 3         print("enter") 4         return self 5     def __exit__(self, type, value, traceback): 6         print("out") 7         del self 8 with test() as m: 9     m.name = 110     print (m.name)

運行結果:

>>> enter>>> 1>>> out

 

6.  __iter__(self) 迭代器(Build-in)

通過__iter__函數獲得一個迭代器對象, 調用迭代器的next方法不斷獲得下一個值.

例子:

 1 class test(object): 2     def __init__(self): 3         self.a = 1 4         self.b = 1 5     def __iter__(self): 6         return self 7     def __next__(self): 8         test = self.a + self.b 9         self.a, self.b = self.b, test10         return self.a11     def next(self):12         return self.__next__13 14 for i in test():15     if i > 1000:16         break17     print(i)

 

聯繫我們

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