Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
166
|
4 章 物件導向的 Python
元類別(Metaclasses
任何的物件,甚至是類別物件,都有一個型別(type)。 Python 中,
型別與類別都是一級物件(first-class objects)。一個類別物件(class
object)的型別也叫做該類別的
元類別
metaclass
4
。一個物件的行為主
要是由該物件的型別所決定。對類別來說,也是如此:一個類別的行為主
要由該類別的元類別所決定。元類別是一個進階主題,而你可能會想要跳
過本節其餘的部分。然而,完全掌握元類別能引導你對 Python 有更深層的
理解,而在非常少數的情況下,定義你自訂的元類別也可能會有用處
5
Python v2 如何決定一個類別的元類別
為了執行一個
class
述句,v2 首先會將基礎類別收集到一個元組
t
(如果
沒有基礎類別,就會是空的)中,然後執行類別主體,將在那裡定義的名
稱儲存到一個暫存的字典
d
中。接著,Python 會判斷
class
述句所創建的
新類別物件
C
的元類別
M
為何。
'__metaclass__'
d
中的一個鍵值,
M
就是
d['__metaclass__']
。因
此,你可以在
C
的類別主體中繫結屬性
__metaclass__
來明確地控制類別
C
的元類別(為了清楚起見,在類別主體的 docstring 後的第一個述句中那樣
做)。否則的話,若
t
是非空的(也就是
C
有一或多個基礎類別),
M
就是
C
的基礎類別的所有元類別中,
leafmost
最子葉
的元類別(也就是說,是
C
的基礎類別的所有其他元類別的子類別的那個元類別 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

利用 Python 进行数据分析(原书第2版)

利用 Python 进行数据分析(原书第2版)

Wes McKinney

Publisher Resources

ISBN: 9789864766819