python中的元類_Python中的元類

python中的元類

Python元類 (Python metaclass)

A metaclass is the class of a class. A class defines how an instance of a class i.e.; an object behaves whilst a metaclass defines how a class behaves. A class is an instance of a metaclass.

元類是類的類。 一個類定義了一個類的實例。 一個對象的行為而元類定義了一個類的行為。 類是元類的實例。

A metaclass is most commonly used as a class-factory. While an object is created by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the __init__ and __new__ methods, metaclasses allows implementing 'additional things' when creating a class, like replace the class with something else entirely.

元類最常用作類工廠。 當通過調用類創建對象時,Python通過調用元類創建一個新類(執行“ class”語句時)。 與__init____new__方法結合使用,元類允許在創建類時實現“其他東西”,例如用其他東西完全替換該類。

When the class statement is executed, Python first executes the body of the class statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the base classes of the class-to-be (metaclasses are inherited), at the __metaclass__ attribute of the class-to-be (if any) or the __metaclass__ global variable. The metaclass is then called with the name, bases, and attributes of the class to instantiate it.

當執行class語句時,Python首先將class語句的主體作為普通代碼塊執行。 生成的名稱空間(字典)保留了將來類的屬性。 通過查看待定類的基類(繼承了元類 ), 待定類的__metaclass__屬性(如果有)或__metaclass__全局變量來確定元類。 然后使用該類的名稱,基數和屬性調用該元類以實例化它。

The usecases of metaclass can be numerous, like

元類的用例可以很多,例如

  1. Logging and profiling

    記錄和分析

  2. Dynamically adding new methods

    動態添加新方法

  3. Dynamic resource locking/synchronization

    動態資源鎖定/同步

  4. Registering the class at creation

    創建時注冊課程

定義元類 (Defining Metaclass)

Metaclass are defined just like any other class, but they inherit from 'type'. The metaclass is automatically invoked when the class statement using metaclass ends. If a metaclass keyword is used on the other hand, the class assigned to it will be invoked instead of 'type',

元類的定義與其他任何類一樣,但是它們從'type'繼承。 當使用元類的類語句結束時, 元類將自動被調用。 另一方面,如果使用metaclass關鍵字 ,則會調用分配給它的類,而不是'type'

>>> class MyMeta(type):
...     def __new__(cls, clsname, superclasses, attrdict):
...             print("class name:{}".format(clsname))
...             print("super class name{}".format(superclasses))
...             print("attribute dict{}".format(attrdict))
...             return type.__new__(cls, clsname, superclasses, attrdict)
...

Use the above class like below,

使用上面的類,如下所示,

>>> class test1:
...     pass
...
>>> class test2(test1, metaclass=MyMeta):
...     pass
...

Output (Observe that we see that MyMeta__new__ is invoked and not from 'type')

輸出(觀察到我們看到MyMeta__new__被調用,而不是從'type'中調用)

class name:test2
super class name(<class '__main__.test1'>,)
attribute dict{'__module__': '__main__', '__qualname__': 'test2'}
>>>

使用元類創建單例 (Creating Singletons using Metaclass)

The singleton pattern is a design pattern that puts a constraint in the instantiation of a class to only one object. Singleton design pattern is used in cases where exactly one object is required.

單例模式是一種設計模式,它在類的實例化中僅對一個對象施加了約束。 單例設計模式用于僅需要一個對象的情況。

>>> class MySingleton(type):
...     _instances = {}
...     def __call__(cls, *args, **kwargs):
...             if cls not in cls._instances:
...                     cls._instances[cls] = super(MySingleton,cls).__call__(*args, **kwargs)
...             return cls._instances[cls]
>>> class SingletonClass(metaclass= MySingleton):
...     pass
...
>>> class RegularClass():
...     pass
...
>>> test1 = SingletonClass()
>>> test2 = SingletonClass()
>>>
>>> print(test1 == test2)
True
>>> test1 = RegularClass()
>>> test2 = RegularClass()
>>> print(test1 == test2)
False

翻譯自: https://www.includehelp.com/python/metaclass.aspx

python中的元類

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377029.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377029.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377029.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

MySQL 8.0.22執行器源碼分析HashJoin —— 一些初始化函數的細節步驟

目錄InitRowBuffer&#xff08;101行~126行&#xff09;InitProbeIterator&#xff08;142行~153行&#xff09;*HashJoinIterator* 的Init&#xff08;155行~240行&#xff09;InitializeChunkFiles&#xff08;364行~401行&#xff09;InitWritingToProbeRowSavingFile&#…

c語言的宏定義學習筆記

宏定義 在預處理之前&#xff0c;c預處理器會對代碼進行翻譯&#xff0c;譬如用blank替換注釋&#xff0c;去掉多余的空格&#xff0c;刪除末尾的\來拼接行等。 例如&#xff1a; int /*注釋*/ x; 會被翻譯成 int x; printf("this is a s\ entence."); 會被翻譯成 pr…

攝氏溫度轉換華氏溫度_什么是攝氏溫度?

攝氏溫度轉換華氏溫度攝氏溫度 (Celsius) Celsius is a temperature measuring scale which as a SI unit derived from the seven base units stated and described by the International System of Units (SI). 攝氏溫度是一種溫度測量刻度&#xff0c;它是由國際單位制(SI)所…

別人的算法學習之路

http://www.cnblogs.com/figure9/p/3708351.html 我的算法學習之路 關于 嚴格來說&#xff0c;本文題目應該是我的數據結構和算法學習之路&#xff0c;但這個寫法實在太繞口——況且CS中的算法往往暗指數據結構和算法&#xff08;例如算法導論指的實際上是數據結構和算法導論&a…

git config命令使用第二篇——section操作,多個key值操作,使用正則

接上一篇&#xff0c;git config命令使用第一篇——介紹&#xff0c;基本操作&#xff0c;增刪改查:http://blog.csdn.net/hutaoer06051/article/details/8275069 1. 刪除一個section 命令參數 --remove-section 格式&#xff1a;git config [--local|--global|--system] --rem…

MySQL面試準備——64頁pdf

本筆記為以前整理的零碎的關于Mysql的知識點&#xff0c;有深入源碼的也有淺層的八股。已經被我整理成了一個pdf。 實習崗位正好也是和數據庫內核有關的&#xff0c;之后應該還會更新。做個整理&#xff0c;方便秋招的時候快速回顧吧。 鏈接&#xff1a;鏈接 提取碼&#xff1a…

python點圖_Python | 點圖

python點圖The dot plot is a type of data representation in which each data-point in the figure is represented as a dot. Dot plot underlies discrete functions unlike a continuous function in a line plot. Each value could be correlated but cannot be connecte…

SAP-MM:發票、貸方憑證、事后借記、后續貸記

發票和事后借記 相同點&#xff1a;增加對供應商的應付款 不同點&#xff1a;針對同一訂單收貨&#xff0c;發票要先于事后借記&#xff08;事后借記是對供應商后期發票金額的補充&#xff09;&#xff1b;發票和金額、訂單數量有關系&#xff0c;而事后借記只是訂單金額調整的…

Dijkstra for MapReduce (1)

<math xmlns"http://www.w3.org/1998/Math/MathML"><mi>x</mi><mo>,</mo><mi>y</mi><mo>&#x2208;<!-- ∈ --></mo><mi>X</mi> </math> 準備研究一下Dijkstra最短路徑算法Hadoop上…

sql的外鍵約束和主鍵約束_SQL約束

sql的外鍵約束和主鍵約束SQL | 約束條件 (SQL | Constraints) Constraints are the guidelines implemented on the information sections of a table. These are utilized to restrict the kind of information that can go into a table. This guarantees the precision and …

nios pio interrupt 的使能

關于nios 中的中斷&#xff0c;因為要16c550中需要nios的中斷環境去測試&#xff0c;所以就用到了中斷。 硬件&#xff1a;在nios中添加硬件PIO,但是要使能中斷功能。如下圖所示&#xff1a; 系統列化&#xff0c;PIO的連接就不說了。但是要注意兩地方&#xff1a;edge type&am…

《單線程的build hash table、write rows to chunks、hash join的步驟以及流程圖》

Build Hash Table流程 1、初始化row buffer2、從build input table中讀一行3、若讀完build input table所有row&#xff0c;返回狀態READING_ROW_FROM_PROBE_item4、否則&#xff0c;向hash map中寫入一條row5、如果hash map 寫入成功&#xff0c;返回2&#xff0c;繼續執行6、…

在Scala的溪流

Scala | 流 (Scala | Streams) Stream in Scala is a type of lazy val. It is a lazy val whose elements are evaluated only when they are used in the program. Lazy initialization is a feature of Scala that increases the performance of the program. Scala中的Stre…

適合高速驅動電路的推挽電路

http://www.dzsc.com/data/html/2008-9-10/69023.html 圖1是使用NPN/PNP型晶體管的互補推挽電路&#xff0c;適于驅動功率MOSFET的門極。此電路雖然具有門極電流的驅動能力&#xff0c;但射極輸出波形不能比輸人信號快。 圖2是此電路的開關波形。它表示出tf、tr都快&#xff0c…

cholesky分解

接著LU分解繼續往下&#xff0c;就會發展出很多相關但是并不完全一樣的矩陣分解&#xff0c;最后對于對稱正定矩陣&#xff0c;我們則可以給出非常有用的cholesky分解。這些分解的來源就在于矩陣本身存在的特殊的 結構。對于矩陣A&#xff0c;如果沒有任何的特殊結構&#xff0…

socket編程常見函數使用方法

socket知識 有了IP地址&#xff0c;socket可知道是與哪一臺主機的哪一個進程通信 有了端口號&#xff0c;就知道是這個進程的哪一個套接字進行傳輸 應用進程使用描述符與它的套接字進行通信&#xff0c;也就是說一個進程創建一個套接字時就會返回一個套接字描述符 socket的…

需求變更流程不規范,項目早晚得完蛋

很多人&#xff0c;做的項目不少&#xff0c;但成功的不多。這是一個值得深思的問題。 項目為什么這么難做&#xff1f;需求蔓延&#xff0c;客戶難搞是基本原因。 如何解決上述問題&#xff1a; 1&#xff09;強化需求調研和項目設計在整個項目中的重要性 一般地&#xff0c;需…

html 表格套表格_HTML表格

html 表格套表格A table is a set of rows and columns, which could be created on a webpage in HTML, by <table> tag. The tabular representation of complex data makes it readable. 表格是一組行和列&#xff0c;可以通過<table>標簽在HTML網頁上創建。 復…

Android判斷界面

仿造微信&#xff0c;第一次進入去引導界面&#xff0c;否則進啟動界面。 package edu.hpu.init;import edu.hpu.logic.R;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.os.H…

HDU計算機網絡系統2021復習提綱

目錄計算機網絡系統的主要功能TCP/IP模型與OSI模型的層次結構及各層功能。&#xff08;掌握&#xff09;TCP/IP參考模型各層次所對應的主要設備局域網的體系結構與IEEE.802標準數據鏈路層的編址方式和主要設備原理數據鏈路層CSMA/CD的技術原理交換機VLAN原理與劃分方法數據鏈路…