自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python內(nèi)置方法和屬性應(yīng)用:反射和單例

開發(fā) 后端
筆者最近在做項(xiàng)目框架時(shí)涉及到一些不是很常用的方法和屬性,在本文中和大家做下分享。

[[330687]]

1. 前言

python除了豐富的第三方庫(kù)外,本身也提供了一些內(nèi)在的方法和底層的一些屬性,大家比較常用的如dict、list、set、min、max、range、sorted等。筆者最近在做項(xiàng)目框架時(shí)涉及到一些不是很常用的方法和屬性,在本文中和大家做下分享。

2. 內(nèi)置方法和函數(shù)介紹

  •  enumerate

    如果你需要遍歷可迭代的對(duì)象,有需要獲取它的序號(hào),可以用enumerate, 每一個(gè)next返回的是一個(gè)tuple 

  1. list1 = [1, 2, 3, 4]  
  2.   list2 = [4, 3, 2, 1]  
  3.   for idx, value in enumerate(list1):  
  4.       print(idx, value, list2[idx])  
  5.   # 0 1 4  
  6.   # 1 2 3  
  7.   # 2 3 2  
  8.   # 3 4 1 
  •  zip zip從參數(shù)中的多個(gè)迭代器取元素組合成一個(gè)新的迭代器; 
  1. # 給list加上序號(hào)  
  2.   b = [4, 3, 2, 1]  
  3.   for i in zip(range(len(b)), b):  
  4.       print(i)  
  5.   # (0, 4)  
  6.   # (1, 3)  
  7.   # (2, 2)  
  8.   # (3, 1) 
  •  globals():一個(gè)描述當(dāng)前執(zhí)行過程中全局符號(hào)表的字典,可以看出你執(zhí)行的所有過程
  •  id(object):python對(duì)象的唯一標(biāo)識(shí)
  •  staticmethod 類靜態(tài)函數(shù)注解   
  1. @staticmethod    
  2.     def test():   
  3.         print('this is static method')  
  4.     Foo.test = test  
  5.     Foo.test() 
  •  類的屬性 我們來看下一個(gè)類的申明,如下:   
  1. class Foo():  
  2.        """this is test class"""  
  3.        def __init__(self, name):  
  4.            self.name = name   
  5.        def run(self):  
  6.            print('running')  
  1. # 列出類的所有成員和屬性  
  2.  dir(Foo)  
  3.  ['__class__',  
  4.  '__delattr__',  
  5.  '__dict__',  
  6.  '__dir__',  
  7.  '__doc__',  
  8.  '__eq__',  
  9.  '__format__', 
  10.  '__ge__',  
  11.  '__getattribute__',  
  12.  '__gt__',  
  13.  '__hash__',  
  14.  '__init__',  
  15.  '__init_subclass__',  
  16.  '__le__',  
  17.  '__lt__',  
  18.  '__module__',  
  19.  '__ne__',  
  20.  '__new__',  
  21.  '__reduce__',  
  22.  '__reduce_ex__',  
  23.  '__repr__',  
  24.  '__setattr__',  
  25.  '__sizeof__',  
  26.  '__str__',  
  27.  '__subclasshook__',  
  28.  '__weakref__',  
  29.  'run']  
  30.  # 類的注釋  
  31.  Foo.__doc__  
  32.  # 'this is test class'  
  33.  # 類自定義屬性  
  34.  Foo.__dict__  
  35.  mappingproxy({'__module__': '__main__',  
  36.            '__doc__': 'this is test class',  
  37.            '__init__': <function __main__.Foo.__init__(self, name)> 
  38.            'run': <function __main__.Foo.run(self)> 
  39.            '__dict__': <attribute '__dict__' of 'Foo' objects> 
  40.            '__weakref__': <attribute '__weakref__' of 'Foo' objects>})  
  41.  # 類的父類  
  42.  Foo.__base__  
  43.  # 類的名字  
  44.  Foo.__name__ 

 類的實(shí)例化和初始化   

  1. # python類先通過__new__實(shí)例化,再調(diào)用__init__進(jìn)行初始化類成員  
  2.     foo = Foo('milk') 

類的屬性添加和訪問   

  1. # 類的訪問  
  2.    foo.name  
  3.    foo.run() 
  4.    # 可以通過setattr 動(dòng)態(tài)的添加屬性  
  5.    def method():  
  6.        print("cow")  
  7.    setattr(foo, "type", "cow")  
  8.    setattr(foo, "getcow", method)  
  9.    # cow  
  10.    foo.type  
  11.    foo.getcow()  
  12.    # 動(dòng)態(tài)刪除屬性 delattr  
  13.    delattr(foo, "type")  
  14.    # getattr 獲取成員屬性  
  15.    if hasattr(foo, "run"): # 判斷是否有屬性  
  16.        func = getattr(foo, "run")  
  17.        func() 

3. 單例模式應(yīng)用

單例模式(Singleton Pattern)是 Java 中最簡(jiǎn)單的設(shè)計(jì)模式之一。單例模式要求在類的使用過程中只實(shí)例化一次,所有對(duì)象都共享一個(gè)實(shí)例。創(chuàng)建的方法是在實(shí)例的時(shí)候判斷下是否已經(jīng)實(shí)例過了,有則返回實(shí)例化過的全局實(shí)例。python是如何實(shí)現(xiàn)的呢?關(guān)鍵是找到實(shí)例化的地方,對(duì)就是前面說的__new__ 

  1. class Singleton(object):  
  2.     def __new__(cls, *args, **kwargs):  
  3.         if not hasattr(cls, '_instance'):  
  4.             cls._instance = object.__new__(cls)  
  5.         return cls._instance   
  6.     def __init__(self, name):  
  7.         self.name = name  
  8. a = Singleton('name1')  
  9. b = Singleton('name2')  
  10. print(id(a), id(b))  
  11. print(a.name, b.name)  
  12. # 1689352213112 1689352213112  
  13. # name2 name2 

4. 反射應(yīng)用

反射在許多框架中都有使用到,簡(jiǎn)單就是通過類的名稱(字符串)來實(shí)例化類。一個(gè)典型的場(chǎng)景就是通過配置的方式來動(dòng)態(tài)控制類的執(zhí)行,比如定時(shí)任務(wù)的執(zhí)行,通過維護(hù)每個(gè)定時(shí)任務(wù)類的執(zhí)行時(shí)間,在執(zhí)行時(shí)間到的時(shí)候,通過反射方式實(shí)例化類,執(zhí)行任務(wù),在java中也非常的常見。

python的實(shí)現(xiàn)可以通過上面說的getattr獲取模塊中的類, 通過methodcaller來調(diào)用方法。我們來看一個(gè)簡(jiǎn)單的例子 

  1. import importlib  
  2. from operator import methodcaller  
  3. class Foo(): 
  4.      """this is test class"""  
  5.     def __init__(self, name):  
  6.         self.name = name   
  7.     def run(self, info):  
  8.         print('running %s' % info)  
  9. # 類所在的模塊,默認(rèn)情況__main__, 可以通過Foo.__dict__ 中'__module__'獲取  
  10. api_module = importlib.import_module('__main__')   
  11. # getattr獲取模塊中的類, 這里Foo是字符串哦  
  12. clazz = getattr(api_module, 'Foo')  
  13. # 實(shí)例化  
  14. params = ["milk"]  
  15. instance = clazz(*params)  
  16. # 方法調(diào)用, 方法也是字符串methodcaller(方法名, 方法參數(shù))  
  17. task_result = methodcaller("run", "reflection")(instance)  
  18. # running reflection 

5. 總結(jié)

本文通過分享了python內(nèi)置方法和屬性, 并在單例模式和反射中進(jìn)行應(yīng)用。希望對(duì)你有幫助,歡迎交流@mintel 要點(diǎn)總結(jié)如下:

  •  dir下類
  •  查看類自定義屬性__dict__
  •  __new__實(shí)例化類,__init__初始化類
  •  getattr 獲取屬性
  •  setattr 設(shè)置屬性
  •  記住importlib和methodcaller 

 

責(zé)任編輯:龐桂玉 來源: Python中文社區(qū)
相關(guān)推薦

2020-09-16 12:18:28

GoJava模式

2024-03-18 08:33:16

2023-09-21 22:19:03

Python編程語(yǔ)言

2020-02-05 21:46:58

工業(yè)物聯(lián)網(wǎng)IIOT物聯(lián)網(wǎng)

2023-03-21 15:21:52

開發(fā)程序設(shè)計(jì)static

2023-11-20 14:41:34

Python屬性

2024-11-06 16:13:00

Python單例模式

2023-10-11 13:13:46

?PostmanJavaScrip

2019-07-03 09:46:31

物聯(lián)網(wǎng)傳感器機(jī)器學(xué)習(xí)

2010-07-06 16:38:47

UML用例建模

2021-06-29 11:09:59

區(qū)塊鏈區(qū)塊鏈技術(shù)比特幣

2016-03-24 11:26:21

runtime成員變量屬性

2009-08-18 13:41:40

WebBrowser控

2009-09-17 16:45:56

C#數(shù)組

2010-06-29 16:43:54

UML用例建模

2010-06-17 12:32:54

UML用例建模

2010-07-08 16:34:01

UML包圖

2025-03-04 08:37:28

2010-08-31 15:24:43

CSSpositionabsolute

2010-09-28 10:33:59

HTML DOM Ch
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)