Python內(nèi)置方法和屬性應(yīng)用:反射和單例(推薦)
1. 前言
python除了豐富的第三方庫外,本身也提供了一些內(nèi)在的方法和底層的一些屬性,大家比較常用的如dict、list、set、min、max、range、sorted等。筆者最近在做項目框架時涉及到一些不是很常用的方法和屬性,在本文中和大家做下分享。
2. 內(nèi)置方法和函數(shù)介紹
enumerate
如果你需要遍歷可迭代的對象,有需要獲取它的序號,可以用enumerate, 每一個next返回的是一個tuple
list1 = [1, 2, 3, 4] list2 = [4, 3, 2, 1] for idx, value in enumerate(list1): print(idx, value, list2[idx]) # 0 1 4 # 1 2 3 # 2 3 2 # 3 4 1
zip zip從參數(shù)中的多個迭代器取元素組合成一個新的迭代器;
# 給list加上序號 b = [4, 3, 2, 1] for i in zip(range(len(b)), b): print(i) # (0, 4) # (1, 3) # (2, 2) # (3, 1)
- globals():一個描述當前執(zhí)行過程中全局符號表的字典,可以看出你執(zhí)行的所有過程
- id(object):python對象的唯一標識
- staticmethod 類靜態(tài)函數(shù)注解
@staticmethod
def test():
print('this is static method')
Foo.test = test
Foo.test()
類的屬性 我們來看下一個類的申明,如下:
class Foo():
"""this is test class"""
def __init__(self, name):
self.name = name
def run(self):
print('running')
# 列出類的所有成員和屬性
dir(Foo)
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'run']
# 類的注釋
Foo.__doc__
# 'this is test class'
# 類自定義屬性
Foo.__dict__
mappingproxy({'__module__': '__main__',
'__doc__': 'this is test class',
'__init__': <function __main__.Foo.__init__(self, name)>,
'run': <function __main__.Foo.run(self)>,
'__dict__': <attribute '__dict__' of 'Foo' objects>,
'__weakref__': <attribute '__weakref__' of 'Foo' objects>})
# 類的父類
Foo.__base__
# 類的名字
Foo.__name__
類的實例化和初始化
# python類先通過__new__實例化,再調(diào)用__init__進行初始化類成員
foo = Foo('milk')
類的屬性添加和訪問
# 類的訪問
foo.name
foo.run()
# 可以通過setattr 動態(tài)的添加屬性
def method():
print("cow")
setattr(foo, "type", "cow")
setattr(foo, "getcow", method)
# cow
foo.type
foo.getcow()
# 動態(tài)刪除屬性 delattr
delattr(foo, "type")
# getattr 獲取成員屬性
if hasattr(foo, "run"): # 判斷是否有屬性
func = getattr(foo, "run")
func()
3. 單例模式應(yīng)用
單例模式(Singleton Pattern)是 Java 中最簡單的設(shè)計模式之一。單例模式要求在類的使用過程中只實例化一次,所有對象都共享一個實例。創(chuàng)建的方法是在實例的時候判斷下是否已經(jīng)實例過了,有則返回實例化過的全局實例。python是如何實現(xiàn)的呢?關(guān)鍵是找到實例化的地方,對就是前面說的__new__
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls)
return cls._instance
def __init__(self, name):
self.name = name
a = Singleton('name1')
b = Singleton('name2')
print(id(a), id(b))
print(a.name, b.name)
# 1689352213112 1689352213112
# name2 name2
4. 反射應(yīng)用
反射在許多框架中都有使用到,簡單就是通過類的名稱(字符串)來實例化類。一個典型的場景就是通過配置的方式來動態(tài)控制類的執(zhí)行,比如定時任務(wù)的執(zhí)行,通過維護每個定時任務(wù)類的執(zhí)行時間,在執(zhí)行時間到的時候,通過反射方式實例化類,執(zhí)行任務(wù),在java中也非常的常見。
python的實現(xiàn)可以通過上面說的getattr獲取模塊中的類, 通過methodcaller來調(diào)用方法。我們來看一個簡單的例子
import importlib
from operator import methodcaller
class Foo():
"""this is test class"""
def __init__(self, name):
self.name = name
def run(self, info):
print('running %s' % info)
# 類所在的模塊,默認情況__main__, 可以通過Foo.__dict__ 中'__module__'獲取
api_module = importlib.import_module('__main__')
# getattr獲取模塊中的類, 這里Foo是字符串哦
clazz = getattr(api_module, 'Foo')
# 實例化
params = ["milk"]
instance = clazz(*params)
# 方法調(diào)用, 方法也是字符串methodcaller(方法名, 方法參數(shù))
task_result = methodcaller("run", "reflection")(instance)
# running reflection
5. 總結(jié)
本文通過分享了python內(nèi)置方法和屬性, 并在單例模式和反射中進行應(yīng)用。希望對你有幫助,歡迎交流@mintel 要點總結(jié)如下:
- dir下類
- 查看類自定義屬性__dict__
- __new__實例化類,__init__初始化類
- getattr 獲取屬性
- setattr 設(shè)置屬性
- 記住importlib和methodcaller
到此這篇關(guān)于Python內(nèi)置方法和屬性應(yīng)用:反射和單例的文章就介紹到這了,更多相關(guān)Python內(nèi)置方法和屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 提取dict轉(zhuǎn)換為xml/json/table并輸出的實現(xiàn)代碼
這篇文章主要介紹了Python 提取dict轉(zhuǎn)換為xml/json/table并輸出的實現(xiàn)代碼,需要的朋友可以參考下2016-08-08
python tkinter庫實現(xiàn)氣泡屏保和鎖屏
這篇文章主要為大家詳細介紹了python tkinter庫實現(xiàn)氣泡屏保和鎖屏,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07
Python實現(xiàn)簡單的HttpServer服務(wù)器示例
本篇文章主要介紹了Python實現(xiàn)簡單的HttpServer服務(wù)器示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
盤點20個Python數(shù)據(jù)科學庫神器打造數(shù)據(jù)魔法世界
數(shù)據(jù)科學家和分析師常常使用?Python?來處理數(shù)據(jù)、進行分析和可視化,Python生態(tài)系統(tǒng)中有許多庫,但有一些庫是數(shù)據(jù)科學家日常工作中必不可少的,本文將深入介紹20個重要的Python?庫,包括示例代碼和用例2024-01-01
Python標準庫之數(shù)據(jù)庫 sqlite3
這篇文章主要介紹了Python標準庫的數(shù)據(jù)庫 sqlite3的相關(guān)資料,SQLite是一個輕量級、跨平臺的關(guān)系型數(shù)據(jù)庫。它的核心引擎本身不依賴第三方的軟件,使用它也不需要“安裝”。下面文字將對其簡單介紹,需要的小伙伴可以參考下面文章內(nèi)容2021-09-09

