如何動態新增屬性
問題
您的目標是建立一個模仿資料庫結果集的模擬類別。例如,當資料庫查詢返回{'ab':100, 'cd':200} 時,您期望看到:
>>> dummy.ab 100
解決方案
儘管將屬性添加到動態類是可行的,它必須添加到類別本身。
>>> class Foo(object): ... pass ... >>> foo = Foo() >>> foo.a = 3 >>> Foo.b = property(lambda self: self.a + 1) >>> foo.b 4
屬性是描述符的簡單實現,描述符是一個在特定類別上提供自訂屬性處理的物件。它充當 __getattribute__ 中擴展 if 樹的替代品。
當您要求 foo.b 時,Python 會識別出類別上定義的 b 遵循描述符協議,該協議僅指示帶有 的物件get__、__set__ 或 __delete 方法。描述子承擔處理該屬性的責任,提示 Python 呼叫 Foo.b.__get__(foo, Foo),並且傳回值會作為屬性的值傳回給您。在屬性的情況下,這些方法中的每一個都只是呼叫您提供給屬性建構函數的 fget、fset 或 fdel。
描述符是 Python 的機制,用於揭示其整體 OO 實現的複雜性。順便說一句,有一種獨特類型的描述符比屬性更普遍。
>>> class Foo(object): ... def bar(self): ... pass ... >>> Foo().bar <bound method foo.bar of object at>> >>> Foo().bar.__get__ <method-wrapper of instancemethod object at></method-wrapper></bound>
簡單的方法是另一種類型的描述符。它的get 將呼叫實例作為第一個參數作為前綴;本質上,它是這樣做的:
def __get__(self, instance, owner): return functools.partial(self.function, instance)
這可能是描述符僅適用於類別的原因:它們首先形式化了支撐類的機制。它們是規則的例外:毫無疑問,您可以將描述符指派給類,儘管類別本身是類型實例。事實上,嘗試檢索 Foo.bar 仍然會呼叫 property.__get__;然而,描述符在作為類別屬性存取時傳回自身是慣用的。
描述符使大多數 Python 的 OO 系統能夠用 Python 本身編寫。
以上是如何在 Python 中動態為類別新增屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載
最受歡迎的的開源編輯器