Intermediate Python 📂 Class and Object · 10 of 10 234 min read

Python Metaclasses Tutorial

Master Python metaclasses — the classes that create classes. Understand why "everything is an object," how type is the metaclass of every class, how to write your own metaclass to validate class definitions or auto-register subclasses, and when the modern __init_subclass__ hook is cleaner. Includes a cookie-cutter-factory analogy, three animated SVG diagrams (three-level hierarchy, class creation intercept, plugin registry), practical validator and registry examples, plus 10 golden rules.

🌐
SectionSection第 01 节

The Story That Explains Metaclasses 🍪Metaclasses समझाने वाली कहानी 🍪一个讲清元类的故事 🍪

The Cookie-Cutter FactoryCookie-Cutter की Factory饼干模具工厂
Picture three layers in a bakery.

Layer 1 — the cookies. Single cookies on a tray. Each one is a real thing you can eat. These are your instances (like buddy).

Layer 2 — the cookie cutters. Metal shapes — star, heart, moon. Each cutter stamps out many cookies of one shape. These are your classes (like Dog).

Layer 3 — the cutter factory. The machine at the back of the workshop that makes the cutters themselves. Every cutter — star, heart, moon — came from this one machine. This is a metaclass (like type).

Now the twist. In Python, everything is an object — classes too. If a class is an object, something must have made it. That "something" is a metaclass. Python's default metaclass is type — the machine that makes every class you have ever written, from Dog to Vector to BankAccount.

Write your own metaclass, and you change how classes themselves are made. Check rules that every subclass must follow. Register every plugin the moment it is defined. Add methods to every class in a family. It is the deepest hook Python gives you.
बेकरी की तीन परतों की कल्पना कीजिए।

परत 1 — cookies। Tray पर अलग-अलग cookies। हर एक असली चीज़ है जिसे आप खा सकते हैं। ये आपके instances हैं (जैसे buddy)।

परत 2 — cookie cutters। धातु के आकार — तारा, दिल, चाँद। हर cutter एक आकार की कई cookies बनाता है। ये आपकी classes हैं (जैसे Dog)।

परत 3 — cutters की factory। Workshop के पीछे वाली machine जो ख़ुद cutters बनाती है। हर cutter — तारा, दिल, चाँद — इसी एक machine से आया। यही metaclass है (जैसे type)।

अब मोड़। Python में सब कुछ object है — classes भी। अगर class एक object है, तो किसी ने उसे बनाया होगा। वह "कोई" metaclass है। Python का default metaclass type है — वह machine जो आपकी लिखी हर class बनाती है, Dog से Vector से BankAccount तक।

अपना metaclass लिखिए, और आप बदल देते हैं कि classes ख़ुद कैसे बनती हैं। ऐसे नियम जाँचिए जो हर subclass को मानने हों। हर plugin को define होते ही register कीजिए। एक परिवार की हर class में methods जोड़िए। यह Python का सबसे गहरा hook है।
想象面包房里的三个层次。

第 1 层 — 饼干。托盘上一块块的饼干,每一块都是能吃的真东西。这就是你的 实例(比如 buddy)。

第 2 层 — 饼干模具。金属形状 — 星星、爱心、月亮。每个模具都能压出很多同一形状的饼干。这就是你的 类(比如 Dog)。

第 3 层 — 模具工厂。作坊后面那台 制造模具本身 的机器。每个模具 — 星星、爱心、月亮 — 都出自这台机器。这就是 元类(比如 type)。

现在的转折是:在 Python 中,一切皆对象 — 类也是。既然类是对象,就一定有东西创建了它。那个"东西"就是 元类。Python 默认的元类是 type — 它就是创建你写过的每一个类的机器,从 Dog 到 Vector 再到 BankAccount。

写一个自己的元类,你就能改变 类本身是如何被创建的。检查每个子类都必须遵守的规则;在插件被定义的那一刻自动注册它;给一个家族里的每个类添加方法。这是 Python 提供的最深层的钩子。
🏭
The Core Insightमूल बात核心要点

Classes create objects. Metaclasses create classes. Just as an object's behaviour comes from its class, a class's behaviour comes from its metaclass. Python's default metaclass type is invisible until you replace it with your own — then every class that uses your metaclass goes through your creation code.

Classes objects बनाती हैं। Metaclasses classes बनाते हैं। जैसे object का व्यवहार उसकी class से आता है, वैसे class का व्यवहार उसके metaclass से आता है। Python का default metaclass type तब तक दिखता नहीं जब तक आप उसे अपने से न बदलें — फिर आपका metaclass इस्तेमाल करने वाली हर class आपके creation code से होकर गुज़रती है।

类创建对象,元类创建类。就像对象的行为来自它的类,类的行为来自它的元类。Python 默认的元类 type 平时是看不见的,直到你用自己的元类替换它 — 之后 每一个 使用你的元类的类,都会经过你的创建代码。

▶️
This Tutorial Has Six Simulators and a Quizइस Tutorial में छह Simulators और एक Quiz है本教程有六个模拟器和一个小测验

Look for the interactive boxes: the type() Ladder (Section 02), the Class Factory (03), the Metaclass Timeline (05), the Rule Checker (06), the Registry Builder (08) and the Bug Doctor (10). Every result comes from real Python runs.

Interactive डिब्बे खोजें: type() सीढ़ी (Section 02), Class Factory (03), Metaclass Timeline (05), Rule Checker (06), Registry Builder (08) और Bug Doctor (10)। हर नतीजा असली Python runs से है।

请留意这些互动框:type() 阶梯(第 02 节)、类工厂(03)、元类时间线(05)、规则检查器(06)、注册表构建器(08)和 Bug 医生(10)。每个结果都来自真实的 Python 运行。


SectionSection第 02 节

Everything Is an Object — Including Classes 🪜सब कुछ Object है — Classes भी 🪜一切皆对象 — 包括类 🪜

One central truth unlocks metaclasses: classes are objects too. You can pass them around, store them in lists and give them new attributes — and they were themselves made by another class. That maker is type.

एक मूल सच metaclasses को खोलता है: classes भी objects हैं। आप उन्हें पास कर सकते हैं, lists में रख सकते हैं, नए attributes दे सकते हैं — और उन्हें ख़ुद किसी दूसरी class ने बनाया था। वह बनाने वाला type है।

理解元类的关键只有一条:类也是对象。你可以传递它们、放进列表、给它们添加新属性 — 而且它们 本身 也是由另一个类创建的。这个创建者就是 type。

class Dog:
    pass

buddy = Dog()

# buddy is an instance of Dog
print(type(buddy))         # <class '__main__.Dog'>

# Dog is an instance of type - that's the metaclass level
print(type(Dog))           # <class 'type'>

# type is itself an instance of type - the chain stops here
print(type(type))          # <class 'type'>

# Classes have __class__ pointing to their metaclass
print(Dog.__class__)       # <class 'type'>
OUTPUT
<class '__main__.Dog'> <class 'type'> <class 'type'> <class 'type'>
Three Levels — Object ← Class ← Metaclassतीन स्तर — Object ← Class ← Metaclass三个层次 — 对象 ← 类 ← 元类
Object class metaclass hierarchyINSTANCE (object)INSTANCE (object)实例(对象)buddy = Dog()a real dog you can petएक असली कुत्ता一只真实的狗Layer 1परत 1第 1 层the cookiecookie饼干CLASSCLASS类class Dog: ...the blueprint for dogsकुत्तों का नक़्शा狗的蓝图Layer 2परत 2第 2 层the cuttercutter模具METACLASSMETACLASS元类typethe factory that makes classesclasses बनाने वाली factory制造类的工厂Layer 3परत 3第 3 层the factoryfactory工厂type(buddy) → Dogtype(Dog) → typetype(type) → type

Every object has a class. Every class has a metaclass. type is where the chain stops — it is the metaclass of itself.

हर object की class है। हर class का metaclass है। type पर यह सिलसिला रुकता है — वह ख़ुद अपना metaclass है।

每个对象都有类,每个类都有元类。type 是链条的终点 — 它是自己的元类。

🪜 Simulator: The type() Ladder🪜 Simulator: type() सीढ़ी🪜 模拟器:type() 阶梯

Pick anything — an instance, a class, a built-in, a metaclass. The ladder climbs by asking type() again and again until it reaches type. All chains were read from real Python objects.

कुछ भी चुनिए — instance, class, built-in, metaclass। सीढ़ी बार-बार type() पूछकर ऊपर चढ़ती है जब तक type तक न पहुँचे। सारी chains असली Python objects से पढ़ी गई हैं।

随便选一个 — 实例、类、内置类型、元类。阶梯会一次次地调用 type() 向上爬,直到到达 type。所有链条都读取自真实的 Python 对象。

The type() Laddertype() सीढ़ीtype() 阶梯climb with type() until it stopsरुकने तक type() से चढ़िए用 type() 一直爬到终点
Start from:यहाँ से शुरू:起点:
SetupSetup准备代码
Questions Python answersPython जिन सवालों के जवाब देता हैPython 回答的问题

SectionSection第 03 节

Creating a Class Dynamically With type() 🏗️type() से Class बनाना 🏗️用 type() 动态创建类 🏗️

Because type is the metaclass, calling it with three arguments creates a class — no class keyword needed. A class statement works the same way: Python runs the body to build the namespace, then calls the metaclass with the name, the bases and that namespace.

क्योंकि type metaclass है, उसे तीन arguments के साथ बुलाने पर class बन जाती है — class keyword की ज़रूरत नहीं। class statement भी ऐसे ही काम करता है: Python body चलाकर namespace बनाता है, फिर नाम, bases और उस namespace के साथ metaclass को बुलाता है।

因为 type 是元类,用三个参数调用它就能 创建一个类 — 不需要 class 关键字。class 语句也是这样工作的:Python 先运行类体来构建命名空间,然后用名字、基类和这个命名空间调用元类。

# These two forms produce equivalent classes

# Form 1 - the class keyword you already know
class Dog:
    species = "Canis familiaris"
    def bark(self):
        return f"{self.species} says woof"


# Form 2 - the same thing, built by calling type() directly
def bark(self):
    return f"{self.species} says woof"

Dog2 = type(
    "Dog2",                                       # class name
    (),                                           # base classes
    {"species": "Canis familiaris", "bark": bark} # namespace
)

# Both work the same way
print(Dog().bark())       # Canis familiaris says woof
print(Dog2().bark())      # Canis familiaris says woof
print(type(Dog) is type(Dog2))   # True - both classes have type as their metaclass
OUTPUT
Canis familiaris says woof Canis familiaris says woof True
💡
The Three Arguments to typetype के तीन Argumentstype 的三个参数

With three arguments, type creates a class: name (a string), bases (a tuple of parent classes) and namespace (a dict of attributes and methods). With one argument, type(x) just tells you the class of x.

तीन arguments के साथ type class बनाता है: name (string), bases (parent classes का tuple) और namespace (attributes और methods की dict)। एक argument के साथ type(x) बस x की class बताता है।

传三个参数时,type 创建一个类:名字(字符串)、基类(父类元组)和 命名空间(属性和方法的字典)。只传一个参数时,type(x) 只是告诉你 x 的类。

🏭 Simulator: Class Factory🏭 Simulator: Class Factory🏭 模拟器:类工厂

Choose a name, a base class and what goes in the namespace. The same class is written both ways — with class and with type(). For all 32 combinations, both forms were run and gave identical output.

नाम, base class और namespace में क्या जाए, यह चुनिए। वही class दोनों तरह लिखी जाती है — class से और type() से। सभी 32 combinations में दोनों रूप चलाए गए और एक जैसा output मिला।

选择名字、基类以及命名空间里放什么。同一个类会用两种方式写出 — class 语句和 type() 调用。全部 32 种组合都运行了两种写法,输出完全相同。

Class FactoryClass Factory类工厂both forms run · 32 combinationsदोनों रूप चलाए · 32 combinations两种写法都已运行 · 32 种组合
Name:नाम:名字:
Bases:Bases:基类:
Namespace:Namespace:命名空间:
Form 1 — class statementरूप 1 — class statement写法 1 — class 语句
=
Form 2 — calling type()रूप 2 — type() बुलाना写法 2 — 调用 type()
Then we runफिर चलाते हैं然后运行
Output (same for both forms)Output (दोनों रूपों में एक जैसा)输出(两种写法相同)

SectionSection第 04 节

Your First Custom Metaclass 🔧आपका पहला Custom Metaclass 🔧你的第一个自定义元类 🔧

To write a metaclass, subclass type. Override its __new__ or __init__ to run code every time a class using your metaclass is defined. Then attach it with metaclass=YourMeta in the class header.

Metaclass लिखने के लिए type की subclass बनाइए। उसका __new__ या __init__ override कीजिए ताकि आपके metaclass वाली class के define होते ही code चले। फिर class header में metaclass=YourMeta से जोड़िए।

要写一个元类,就继承 type。重写它的 __new__ 或 __init__,让每次 定义 使用该元类的类时都运行你的代码。然后在类头部用 metaclass=YourMeta 把它挂上。

class LoggingMeta(type):
    """A metaclass that announces every class defined with it."""

    def __new__(mcs, name, bases, namespace):
        print(f"[LoggingMeta] creating class {name!r} with {len(namespace)} attrs")
        # Let type do the real creation
        cls = super().__new__(mcs, name, bases, namespace)
        # Free to change the class here - add methods, add attributes...
        cls.created_at = "2026-07-12"
        return cls


class Cat(metaclass=LoggingMeta):
    def meow(self):
        return "meow"


class Dog(metaclass=LoggingMeta):
    def bark(self):
        return "woof"


# The metaclass added created_at to every class
print(Cat.created_at)    # 2026-07-12
print(Dog.created_at)    # 2026-07-12

# type() confirms the metaclass
print(type(Cat))         # <class '__main__.LoggingMeta'>
print(type(Dog))         # <class '__main__.LoggingMeta'>
OUTPUT
[LoggingMeta] creating class 'Cat' with 5 attrs [LoggingMeta] creating class 'Dog' with 5 attrs 2026-07-12 2026-07-12 <class '__main__.LoggingMeta'> <class '__main__.LoggingMeta'>
🐍
Fixed: "3 attrs" Is Now "5 attrs"सुधार: "3 attrs" अब "5 attrs" है已修正:"3 attrs" 现在是 "5 attrs"

The original output said with 3 attrs. That was true up to Python 3.12 (__module__, __qualname__, meow). Python 3.13 adds two more entries to every class namespace — __firstlineno__ and __static_attributes__ — so the real output on Python 3.13.16 is with 5 attrs. Here is exactly what the metaclass receives:

मूल output में with 3 attrs था। यह Python 3.12 तक सही था (__module__, __qualname__, meow)। Python 3.13 हर class namespace में दो और entries जोड़ता है — __firstlineno__ और __static_attributes__ — इसलिए Python 3.13.16 पर असली output with 5 attrs है। Metaclass को असल में यह मिलता है:

原输出写的是 with 3 attrs。这在 Python 3.12 及以前是对的(__module__、__qualname__、meow)。Python 3.13 会给每个类的命名空间再加两项 — __firstlineno__ 和 __static_attributes__ — 所以在 Python 3.13.16 上的真实输出是 with 5 attrs。下面是元类实际收到的内容:

class ShowMeta(type):
    def __new__(mcs, name, bases, namespace):
        print(list(namespace))          # everything the class body produced
        return super().__new__(mcs, name, bases, namespace)


class Cat(metaclass=ShowMeta):
    def meow(self):
        return "meow"
OUTPUT
['__module__', '__qualname__', '__firstlineno__', 'meow', '__static_attributes__']
The Metaclass Steps In During Class CreationClass बनते समय Metaclass बीच में आता है元类在类创建时介入
Metaclass intercepts class creationWHAT YOU WRITEजो आप लिखते हैं你写的class Dog(metaclass=LoggingMeta): def bark(self): return "woof"Python runs the body, then calls the metaclassPython body चलाकर metaclass बुलाता हैPython 运行类体,然后调用元类LoggingMeta.__new__ RUNSLoggingMeta.__new__ चलता हैLoggingMeta.__new__ 运行LoggingMeta.__new__(mcs, "Dog", (), {"bark": bark, ...}) cls = super().__new__(mcs, name, bases, namespace) cls.created_at = "2026-07-12" return clsFINISHED CLASS · ADDED TO BY THE METACLASSतैयार CLASS · METACLASS ने जोड़ा完成的类 · 元类添加了内容Dog.bark, Dog.created_at = "2026-07-12"type(Dog) is LoggingMeta

The metaclass runs when the class is defined — before any instances exist. It is your one chance to shape the class itself.

Metaclass class define होते समय चलता है — किसी instance के बनने से पहले। Class को ख़ुद आकार देने का यही मौक़ा है।

元类在类被定义时运行 — 早于任何实例的出现。这是你塑造类本身的唯一机会。


SectionSection第 05 节

What Do Meta.__new__, __init__ and __call__ Control? ⏱️Meta.__new__, __init__ और __call__ क्या control करते हैं? ⏱️Meta.__new__、__init__ 和 __call__ 分别控制什么?⏱️

🏭
Meta.__new__
runs at class creationclass बनते समय चलता है在创建类时运行
Called before the class exists. Receives mcs, name, bases, namespace and must return the class. The best place to check the namespace or add attributes before the class is finished.
Class बनने से पहले बुलाया जाता है। mcs, name, bases, namespace लेता है और class लौटाना ज़रूरी है। Class पूरी होने से पहले namespace जाँचने या attributes जोड़ने की सबसे अच्छी जगह।
在类存在之前调用。接收 mcs, name, bases, namespace,必须返回类。是在类完成之前 检查 命名空间或 添加属性 的最佳位置。
🛠️
Meta.__init__
runs after class creationclass बनने के बाद चलता है在创建类之后运行
Called after __new__. Receives the new class as cls. The best place to register the class or do other follow-up work.
__new__ के बाद बुलाया जाता है। नई class cls के रूप में मिलती है। Class register करने या बाक़ी काम की सबसे अच्छी जगह।
在 __new__ 之后调用。以 cls 接收新创建的类。是 注册 类或做后续处理的最佳位置。
📞
Meta.__call__
runs on every instantiationहर instance बनाने पर चलता है每次实例化时运行
Called every time you write MyClass(...). It controls how instances are made — the same __call__ idea from the previous tutorial, one level up. It can power singletons and instance caches.
हर बार MyClass(...) लिखने पर बुलाया जाता है। यह तय करता है कि instances कैसे बनें — पिछले tutorial वाला __call__, एक स्तर ऊपर। इससे singletons और instance caches बन सकते हैं।
每次写 MyClass(...) 时都会调用。它控制实例如何被创建 — 就是上一个教程里的 __call__,只是高了一层。可以用来实现单例和实例缓存。
class Meta(type):
    def __new__(mcs, name, bases, namespace):
        print(f"  [Meta.__new__]  creating class {name!r}")
        return super().__new__(mcs, name, bases, namespace)

    def __init__(cls, name, bases, namespace):
        print(f"  [Meta.__init__] class {name!r} is ready")
        super().__init__(name, bases, namespace)

    def __call__(cls, *args, **kwargs):
        print(f"  [Meta.__call__] creating an instance of {cls.__name__}")
        return super().__call__(*args, **kwargs)


print("Defining Dog:")
class Dog(metaclass=Meta):
    def __init__(self, name):
        self.name = name

print("\nCreating buddy:")
buddy = Dog("Buddy")
print(buddy.name)
OUTPUT
Defining Dog: [Meta.__new__] creating class 'Dog' [Meta.__init__] class 'Dog' is ready Creating buddy: [Meta.__call__] creating an instance of Dog Buddy
🔑
Timing Is Everythingसमय ही सब कुछ है时机决定一切

Meta.__new__ and Meta.__init__ run once per class — the moment Python reaches the class statement. Meta.__call__ runs every time you create an instance of that class. That is the difference between "shape the class" and "shape each instance".

Meta.__new__ और Meta.__init__ हर class के लिए एक बार चलते हैं — जैसे ही Python class statement तक पहुँचता है। Meta.__call__ उस class का instance बनाने पर हर बार चलता है। यही "class को आकार देना" और "हर instance को आकार देना" का फ़र्क़ है।

Meta.__new__ 和 Meta.__init__ 每个类只运行 一次 — 就在 Python 执行到 class 语句的那一刻。Meta.__call__ 则在每次创建该类的实例时 都会 运行。这就是"塑造类"和"塑造每个实例"的区别。

⏱️ Simulator: Metaclass Timeline⏱️ Simulator: Metaclass Timeline⏱️ 模拟器:元类时间线

Press the buttons in any order. Defining a class lights up the class-definition lane; creating an instance lights up the instance lane. Try creating Dog("Buddy") before defining Dog. Checked against Python on 300 random sequences.

Buttons किसी भी क्रम में दबाइए। Class define करने पर class-definition lane जलती है; instance बनाने पर instance lane। Dog define करने से पहले Dog("Buddy") बनाकर देखिए। 300 random sequences पर Python से जाँचा गया।

以任意顺序按按钮。定义类会点亮 类定义 通道;创建实例会点亮 实例 通道。试试在定义 Dog 之前先创建 Dog("Buddy")。已在 300 个随机序列上与 Python 对照。

Metaclass TimelineMetaclass Timeline元类时间线300 sequences checked300 sequences जाँचे已核对 300 个序列
Run:चलाएँ:运行:
Class-definition time — once per classClass-definition time — हर class में एक बार类定义时 — 每个类一次
Instance time — every callInstance time — हर call पर实例化时 — 每次调用
The metaclassMetaclass元类
The programProgram程序
OutputOutput输出

SectionSection第 06 节

Practical Example 1 — Enforcing Class Design Rules 📏Practical Example 1 — Class Design के नियम लागू करना 📏实战示例 1 — 强制类设计规则 📏

A metaclass that checks every class it builds. Here every public method name must be lowercase — a small stand-in for the real coding standards a team might want to enforce.

ऐसा metaclass जो अपनी बनाई हर class को जाँचता है। यहाँ हर public method का नाम lowercase होना चाहिए — असली coding standards का एक छोटा उदाहरण जिन्हें कोई team लागू करना चाहे।

一个会检查它创建的每个类的元类。这里要求每个公有方法的名字都必须是小写 — 这是团队可能想强制执行的真实编码规范的一个小例子。

class SnakeCaseMeta(type):
    """Every public method must be snake_case (lowercase)."""

    def __new__(mcs, name, bases, namespace):
        for attr_name, attr_value in namespace.items():
            # Only check callable, public attributes
            if callable(attr_value) and not attr_name.startswith("_"):
                if not attr_name.islower():
                    raise TypeError(
                        f"In class {name!r}: method {attr_name!r} "
                        "must be lowercase (snake_case)"
                    )
        return super().__new__(mcs, name, bases, namespace)


# -- This class is fine - all methods are snake_case --
class Good(metaclass=SnakeCaseMeta):
    def do_something(self):
        return "ok"

    def save_to_disk(self):
        return "saved"

print("Good class created successfully")


# -- This class breaks the rule - refused at DEFINITION time --
try:
    class Bad(metaclass=SnakeCaseMeta):
        def DoSomething(self):        # PascalCase - not allowed
            return "nope"
except TypeError as e:
    print("Blocked:", e)
OUTPUT
Good class created successfully Blocked: In class 'Bad': method 'DoSomething' must be lowercase (snake_case)
🏆
Why This Is Powerfulयह क्यों ताक़तवर है为什么这很强大

The check runs the moment Python finishes the class body — before any code that uses the class runs. It is not a tool you have to remember to run; it is built into the class system. Frameworks such as Django use metaclasses in a similar way to turn class definitions into their own internal setup.

जाँच उसी पल चलती है जब Python class body पूरी करता है — class इस्तेमाल करने वाला कोई code चलने से पहले। यह ऐसा tool नहीं जिसे चलाना याद रखना पड़े; यह class system में ही बना है। Django जैसे frameworks भी इसी तरह metaclasses से class definitions को अपने अंदरूनी setup में बदलते हैं।

检查在 Python 执行完类体的那一刻就会运行 — 早于任何使用这个类的代码。它不是一个需要你记得去运行的工具,而是内建在类系统中的。像 Django 这样的框架也以类似方式用元类把类定义转换成内部配置。

📏 Simulator: Rule Checker📏 Simulator: Rule Checker📏 模拟器:规则检查器

Switch members on and off in the class body. Watch SnakeCaseMeta.__new__ scan the namespace in order: private names and non-callables are skipped, and the first bad name stops the class from being created. All 256 combinations were run in Python.

Class body में members on/off कीजिए। देखिए SnakeCaseMeta.__new__ namespace को क्रम से कैसे जाँचता है: private नाम और non-callables छोड़े जाते हैं, और पहला ग़लत नाम class बनने से रोक देता है। सभी 256 combinations Python में चलाए गए।

在类体中打开或关闭成员。观察 SnakeCaseMeta.__new__ 按顺序扫描命名空间:私有名字和不可调用的属性会被跳过,第一个不合规的名字会阻止类被创建。全部 256 种组合都在 Python 中运行过。

Rule CheckerRule Checker规则检查器256 combinations · real outputs256 combinations · असली outputs256 种组合 · 真实输出
Class body:Class body:类体:
Your classआपकी class你的类
The metaclassMetaclass元类
SnakeCaseMeta scans the namespaceSnakeCaseMeta namespace जाँचता हैSnakeCaseMeta 扫描命名空间
Resultनतीजा结果

SectionSection第 07 节

Practical Example 2 — Auto-Registry of Subclasses 📇Practical Example 2 — Subclasses की Auto-Registry 📇实战示例 2 — 子类自动注册 📇

A metaclass that quietly keeps track of every subclass ever defined. Add a new plugin, and it registers itself — no manual bookkeeping. This pattern sits behind plugin systems, model discovery in ORMs, serializer registries and more.

ऐसा metaclass जो define हुई हर subclass का चुपचाप हिसाब रखता है। नया plugin जोड़िए, और वह ख़ुद register हो जाता है — हाथ से हिसाब नहीं। Plugin systems, ORMs में model discovery, serializer registries वग़ैरह के पीछे यही pattern है।

一个默默记录每个已定义子类的元类。新增一个插件,它就会自动注册 — 不用手工登记。插件系统、ORM 中的模型发现、序列化器注册表等背后都是这个模式。

class PluginRegistry(type):
    """A metaclass that auto-registers every subclass into a shared registry."""

    registry = {}    # one dict for the whole metaclass

    def __init__(cls, name, bases, namespace):
        super().__init__(name, bases, namespace)
        # Don't register the base "Plugin" itself - only its children
        if bases:
            PluginRegistry.registry[name] = cls
            print(f"[registry] Registered {name}")


# The base class - not registered because it has no bases
class Plugin(metaclass=PluginRegistry):
    def run(self, msg):
        raise NotImplementedError


# Every subclass is added to the registry automatically
class EmailPlugin(Plugin):
    def run(self, msg):
        return f"EMAIL: {msg}"

class SMSPlugin(Plugin):
    def run(self, msg):
        return f"SMS: {msg}"

class PushPlugin(Plugin):
    def run(self, msg):
        return f"PUSH: {msg}"


# The registry now holds every plugin - dispatch by name
print()
print("All registered plugins:", list(PluginRegistry.registry))

for plugin_name, plugin_cls in PluginRegistry.registry.items():
    plugin = plugin_cls()
    print(f"  {plugin_name} → {plugin.run('hello')}")
OUTPUT
[registry] Registered EmailPlugin [registry] Registered SMSPlugin [registry] Registered PushPlugin All registered plugins: ['EmailPlugin', 'SMSPlugin', 'PushPlugin'] EmailPlugin → EMAIL: hello SMSPlugin → SMS: hello PushPlugin → PUSH: hello
The Registry Grows With Each Subclassहर Subclass के साथ Registry बढ़ती है注册表随每个子类增长
Plugin auto-registryMETACLASSMETACLASS元类PluginRegistry__init__ sees__init__ हर__init__ 拦截each subclasssubclass देखता है每个子类REGISTRYREGISTRY注册表PluginRegistry.registryclass EmailPlugin(Plugin): def run(self, msg): ..."EmailPlugin": EmailPluginclass SMSPlugin(Plugin): def run(self, msg): ..."SMSPlugin": SMSPluginclass PushPlugin(Plugin): def run(self, msg): ..."PushPlugin": PushPluginno manual registration —हाथ से registration नहीं —无需手工注册 —every subclass adds itselfहर subclass ख़ुद जुड़ती है每个子类自动加入

Every subclass definition triggers PluginRegistry.__init__, which adds the class to the registry. No decorator, no manual step.

हर subclass definition PluginRegistry.__init__ चलाती है, जो class को registry में जोड़ता है। न decorator, न हाथ का काम।

每次定义子类都会触发 PluginRegistry.__init__,把类加入注册表。不需要装饰器,也不需要手工步骤。


SectionSection第 08 节

The Modern Alternative — __init_subclass__ ✨आधुनिक विकल्प — __init_subclass__ ✨现代替代方案 — __init_subclass__ ✨

Python 3.6 added __init_subclass__, which covers most real uses of metaclasses with much less ceremony. If all you need is "run some code every time a subclass is defined", it is almost always the better choice.

Python 3.6 ने __init_subclass__ जोड़ा, जो बहुत कम झंझट के साथ metaclasses के ज़्यादातर असली इस्तेमाल सँभाल लेता है। अगर आपको बस "हर subclass define होने पर कुछ code चलाना" है, तो यह लगभग हमेशा बेहतर है।

Python 3.6 引入了 __init_subclass__,它用少得多的样板代码覆盖了 元类的大多数实际用途。如果你只需要"每定义一个子类就运行一些代码",它几乎总是更好的选择。

# -- The SAME auto-registry pattern - no metaclass needed --
class Plugin:
    registry = {}

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.registry[cls.__name__] = cls
        print(f"[registry] Registered {cls.__name__}")


class EmailPlugin(Plugin):
    def run(self, msg): return f"EMAIL: {msg}"

class SMSPlugin(Plugin):
    def run(self, msg): return f"SMS: {msg}"

print(list(Plugin.registry))    # ['EmailPlugin', 'SMSPlugin']
OUTPUT
[registry] Registered EmailPlugin [registry] Registered SMSPlugin ['EmailPlugin', 'SMSPlugin']
🛡️ Metaclass
You must understand the metaclass ideaMetaclass का विचार समझना ज़रूरी需要理解元类的概念
Wordy: name, bases, namespace parametersलंबा: name, bases, namespace parameters繁琐:name, bases, namespace 参数
Metaclass conflicts when mixing class familiesClass families मिलाने पर metaclass conflicts混合不同类家族时会出现元类冲突
Powerful: full control over class creationताक़तवर: class बनने पर पूरा नियंत्रण强大:完全控制类的创建
Right choice for framework authorsFramework लिखने वालों के लिए सही适合框架作者
✅ __init_subclass__
Just a method on the base classबस base class पर एक method只是基类上的一个方法
Takes cls, **kwargs — minimalcls, **kwargs लेता है — बहुत कम接收 cls, **kwargs — 极简
No metaclass conflictsकोई metaclass conflict नहीं没有元类冲突
Enough for most real needsज़्यादातर असली ज़रूरतों के लिए काफ़ी足以满足大多数实际需求
Right choice for application codeApplication code के लिए सही适合应用代码
💡
The Rule of Thumbअंगूठे का नियम经验法则

"Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't." — Tim Peters. Try __init_subclass__ or a simple class decorator first (decorators are covered in an upcoming tutorial). Reach for a metaclass only when those really don't fit — usually when you must change the class namespace itself before the class is built.

"Metaclasses ऐसा गहरा जादू हैं जिसकी 99% users को कभी चिंता नहीं करनी चाहिए। अगर आप सोच रहे हैं कि क्या आपको इनकी ज़रूरत है, तो नहीं है।" — Tim Peters। पहले __init_subclass__ या सादा class decorator आज़माइए (decorators आने वाले tutorial में)। Metaclass तभी लीजिए जब ये सच में फ़िट न हों — आमतौर पर जब class बनने से पहले namespace ही बदलना हो।

"元类是更深层的魔法,99% 的用户都不必为它操心。如果你在犹豫是否需要它,那你就不需要。" — Tim Peters。先试试 __init_subclass__ 或简单的类装饰器(装饰器将在后续教程讲解)。只有当这些确实不合适时才使用元类 — 通常是在类创建之前必须修改 命名空间本身 的时候。

📇 Simulator: Registry Builder📇 Simulator: Registry Builder📇 模拟器:注册表构建器

Build the plugin family one class at a time with three versions: the metaclass from Section 07, the same metaclass without its if bases: check, and __init_subclass__. Then press Run all. All 105 orderings were run in Python.

Plugin परिवार को एक-एक class करके तीन versions में बनाइए: Section 07 का metaclass, वही metaclass if bases: जाँच के बिना, और __init_subclass__। फिर Run all दबाइए। सभी 105 क्रम Python में चलाए गए।

用三个版本一次一个地构建插件家族:第 07 节的元类、去掉 if bases: 检查的同一个元类,以及 __init_subclass__。然后按 Run all。全部 105 种顺序都在 Python 中运行过。

Registry BuilderRegistry Builder注册表构建器105 orderings checked105 क्रम जाँचे已核对 105 种顺序
Version:Version:版本:
Define:Define:定义:
The code so farअब तक का code目前的代码
Run all
The registryRegistry注册表
OutputOutput输出

SectionSection第 09 节

When to Use a Metaclass (and When Not To) 🧭Metaclass कब लें (और कब नहीं) 🧭何时使用元类(以及何时不用)🧭

✅
Framework BoundariesFramework की सीमाएँ框架内部
framework internalsframework के अंदर框架内部实现
Django models, SQLAlchemy's declarative base, Pydantic — the metaclass turns your class definition into rich internal structures (columns, fields, validators).
Django models, SQLAlchemy का declarative base, Pydantic — metaclass आपकी class definition को अंदरूनी ढाँचों (columns, fields, validators) में बदलता है।
Django 模型、SQLAlchemy 的声明式基类、Pydantic — 元类把你的类定义转换成丰富的内部结构(列、字段、校验器)。
✅
Enforce Coding StandardsCoding Standards लागू करना强制编码规范
structural checksढाँचे की जाँच结构检查
Every class in a family must have certain methods, follow a naming pattern or declare required attributes. The check runs when the class is defined, before any use.
परिवार की हर class में कुछ methods हों, naming pattern माने या ज़रूरी attributes घोषित करे। जाँच class define होते ही चलती है, किसी इस्तेमाल से पहले।
家族中的每个类都必须实现某些方法、遵循命名规则或声明必需属性。检查在类定义时运行,早于任何使用。
✅
Deep Class ChangesClass में गहरे बदलाव深度修改类
namespace changesnamespace बदलाव命名空间改造
Rewrite the namespace before the class exists — collect specially marked methods, add helpers. Something a plain decorator can't do cleanly.
Class बनने से पहले namespace बदलिए — ख़ास चिह्नित methods इकट्ठा करें, helpers जोड़ें। यह सादा decorator साफ़ तरह नहीं कर पाता।
在类存在之前改写命名空间 — 收集特别标记的方法、添加辅助方法。这是普通装饰器难以干净完成的。
❌
Auto-RegistrationAuto-Registration自动注册
use __init_subclass____init_subclass__ लें用 __init_subclass__
Use __init_subclass__ instead. Same result, none of the metaclass complexity, and no metaclass conflicts when mixing with other class families.
इसकी जगह __init_subclass__ लें। वही नतीजा, metaclass की कोई जटिलता नहीं, और दूसरी class families के साथ मिलाने पर metaclass conflicts नहीं।
改用 __init_subclass__。效果相同,没有元类的复杂性,与其他类家族混用时也不会有元类冲突。
❌
SingletonsSingletons单例
use a modulemodule लें用模块
Use a module (imported once) or override __new__ on the class, as in the previous tutorial. A metaclass just to make one class a singleton is overkill.
Module लें (एक बार import) या पिछले tutorial की तरह class पर __new__ override करें। सिर्फ़ एक class को singleton बनाने के लिए metaclass ज़रूरत से ज़्यादा है।
用模块(只导入一次),或像上一个教程那样在类上重写 __new__。只为让一个类成为单例而用元类,未免小题大做。
❌
"Cool" or "Clever" Code"Cool" या "चतुर" Code"炫技"代码
prefer boring codeसादा code चुनें宁要朴素代码
Metaclasses cost every reader extra effort. If your goal is not a real framework feature, that cost is not worth it.
Metaclasses हर पढ़ने वाले से अतिरिक्त मेहनत माँगते हैं। अगर आपका लक्ष्य असली framework feature नहीं, तो यह क़ीमत चुकाने लायक़ नहीं।
元类会让每位读者多花力气。如果你的目标不是真正的框架功能,这个代价不值得。

SectionSection第 10 节

Common Mistakes (and Fixes) 🩹आम ग़लतियाँ (और उनके हल) 🩹常见错误(及修正)🩹

Mistakeग़लती错误What goes wrongक्या बिगड़ता है会出什么问题Fixहल修正
Forgetting to return from Meta.__new__Meta.__new__ से return भूलना忘记在 Meta.__new__ 中 returnThe class name ends up bound to NoneClass का नाम None से जुड़ जाता है类名最终绑定到 NoneAlways end __new__ with return cls__new__ को हमेशा return cls से ख़त्म करें__new__ 末尾始终写 return cls
Using self instead of mcs / clsmcs / cls की जगह self用 self 代替 mcs / clsConfusing. In __new__ the first argument is mcs (the metaclass); in __init__/__call__ it is cls (the class being made or called)उलझन भरा। __new__ में पहला argument mcs (metaclass) है; __init__/__call__ में cls (बन रही या बुलाई जा रही class)容易混淆。在 __new__ 中第一个参数是 mcs(元类);在 __init__/__call__ 中是 cls(正在创建或被调用的类)Follow the convention: def __new__(mcs, name, bases, ns), def __init__(cls, ...)परंपरा मानें: def __new__(mcs, name, bases, ns), def __init__(cls, ...)遵循约定:def __new__(mcs, name, bases, ns)、def __init__(cls, ...)
Changing a copy of namespace but passing the original to super().__new__namespace की copy बदलना पर super().__new__ को original देना修改了 namespace 的副本,却把原件传给 super().__new__Your changes are silently droppedआपके बदलाव चुपचाप खो जाते हैं你的修改被悄悄丢弃Pass the updated namespace: super().__new__(mcs, name, bases, new_ns)बदला हुआ namespace दें: super().__new__(mcs, name, bases, new_ns)传入更新后的命名空间:super().__new__(mcs, name, bases, new_ns)
Metaclass conflict in multiple inheritanceMultiple inheritance में metaclass conflict多重继承中的元类冲突TypeError: metaclass conflict when parents have unrelated metaclassesParents के अलग-अलग metaclasses होने पर TypeError: metaclass conflict父类的元类互不相关时出现 TypeError: metaclass conflictMake one metaclass a subclass of the other, or use __init_subclass__एक metaclass को दूसरे की subclass बनाएँ, या __init_subclass__ लें让一个元类继承另一个,或改用 __init_subclass__
Putting namespace work in Meta.__init__Namespace का काम Meta.__init__ में रखना把命名空间相关的工作放进 Meta.__init__The class already exists — changing the namespace dict there has no effectClass पहले से बन चुकी है — वहाँ namespace dict बदलने का कोई असर नहीं类已经存在 — 此时修改 namespace 字典没有任何效果Do namespace work in __new__. Keep __init__ for follow-up workNamespace का काम __new__ में करें। __init__ बाद के काम के लिए रखें命名空间相关工作放在 __new__ 中,__init__ 留给后续处理
Registering the base class along with subclassesSubclasses के साथ base class भी register करना把基类和子类一起注册The registry holds the base too — run() on it raises NotImplementedErrorRegistry में base भी आ जाता है — उस पर run() NotImplementedError देता है注册表里也有基类 — 调用它的 run() 会抛出 NotImplementedErrorCheck if bases: — register only classes that have a parentif bases: जाँचें — सिर्फ़ parent वाली classes register करें检查 if bases: — 只注册有父类的类
Using a metaclass when a class decorator would doजहाँ class decorator काफ़ी हो, वहाँ metaclass类装饰器就能解决却用了元类Extra complexity other developers must decodeअतिरिक्त जटिलता जिसे दूसरे developers को समझना पड़ता है增加了其他开发者必须理解的复杂性Prefer decorators, __init_subclass__ or plain code. A metaclass is the last resortDecorators, __init_subclass__ या सादा code चुनें। Metaclass आख़िरी उपाय है优先用装饰器、__init_subclass__ 或普通代码。元类是最后的手段

🩺 Simulator: Bug Doctor🩺 Simulator: Bug Doctor🩺 模拟器:Bug 医生

Five of these mistakes, run for real. Buggy code on the left, fixed code on the right, changed lines marked.

इनमें से पाँच ग़लतियाँ, असली run में। बाईं ओर buggy code, दाईं ओर ठीक किया हुआ, बदली lines चिह्नित।

其中五个错误的真实运行。左边是有 bug 的代码,右边是修正后的代码,改动的行已标出。

Bug DoctorBug DoctorBug 医生5 bugs · real outputs5 bugs · असली outputs5 个 bug · 真实输出
❌ BuggyBuggy有 bug
✅ Fixedठीक किया已修正

SectionSection第 11 节

Quick Reference 📋Quick Reference 📋速查表 📋

Taskकाम任务SyntaxSyntax语法Notesनोट说明
Default metaclassDefault metaclass默认元类typeEvery class that does not choose another uses typeजो class दूसरा नहीं चुनती, वह type इस्तेमाल करती है没有另选元类的类都使用 type
Get an object's classObject की class获取对象的类type(obj)Usually the same as obj.__class__आमतौर पर obj.__class__ जैसा通常与 obj.__class__ 相同
Get a class's metaclassClass का metaclass获取类的元类type(SomeClass)Same idea, one level upवही विचार, एक स्तर ऊपर同样的思路,高一层
Create a class dynamicallyClass बनाना (dynamic)动态创建类type(name, bases, namespace)The three-argument form of type()type() का तीन-argument रूपtype() 的三参数形式
Custom metaclassCustom metaclass自定义元类class MyMeta(type): ...Subclass typetype की subclass继承 type
Attach it to a classClass से जोड़ना挂到类上class C(metaclass=MyMeta):Keyword in the class headerClass header में keyword类头部中的关键字参数
Step into class creationClass बनने में दख़ल介入类的创建def __new__(mcs, name, bases, ns):Runs once per class definitionहर class definition पर एक बार每个类定义运行一次
Follow-up on a classClass पर बाद का काम类创建后的处理def __init__(cls, name, bases, ns):The class exists here; register it, etc.यहाँ class बन चुकी है; register करें, वग़ैरह此时类已存在;可注册等
Step into instance creationInstance बनने में दख़ल介入实例的创建def __call__(cls, *a, **kw):Runs every time MyClass(...) is calledहर बार MyClass(...) बुलाने पर每次调用 MyClass(...) 时运行
Modern alternativeआधुनिक विकल्प现代替代方案def __init_subclass__(cls, **kw):No metaclass needed for most casesज़्यादातर मामलों में metaclass की ज़रूरत नहीं大多数情况下无需元类

SectionSection第 12 节

Golden Rules and Quiz 🏆सुनहरे नियम और Quiz 🏆黄金法则与小测验 🏆

🏭 Metaclasses — Rules to RememberMetaclasses — याद रखने वाले नियम元类 — 必须记住的规则
1
Classes are objects. Every class is an instance of some metaclass, and Python's default is type. This one sentence explains the whole metaclass system.
Classes objects हैं। हर class किसी metaclass का instance है, और Python का default type है। यही एक वाक्य पूरे metaclass system को समझाता है।
类是对象。每个类都是某个元类的实例,Python 的默认元类是 type。这一句话就解释了整个元类系统。
2
A metaclass is just type with your own __new__, __init__ or __call__. Subclass type, add the hooks you need, attach with metaclass=.
Metaclass बस type है जिसमें आपके अपने __new__, __init__ या __call__ हैं। type की subclass बनाइए, ज़रूरी hooks जोड़िए, metaclass= से जोड़िए।
元类就是带有你自己的 __new__、__init__ 或 __call__ 的 type。继承 type,加上需要的钩子,用 metaclass= 挂上。
3
Meta.__new__ runs before the class exists — the place to check or change the namespace. Meta.__init__ runs after — the place to register. Meta.__call__ runs on every instantiation.
Meta.__new__ class बनने से पहले चलता है — namespace जाँचने या बदलने की जगह। Meta.__init__ बाद में चलता है — register करने की जगह। Meta.__call__ हर instance बनाने पर चलता है।
Meta.__new__ 在类存在 之前 运行 — 用来检查或修改命名空间。Meta.__init__ 在 之后 运行 — 用来注册。Meta.__call__ 在每次实例化时运行。
4
Prefer __init_subclass__ when all you need is "do something for every subclass". It covers most real metaclass uses with none of the complexity, and never causes metaclass conflicts.
जब बस "हर subclass के लिए कुछ करना" हो, तो __init_subclass__ चुनें। यह बिना जटिलता के ज़्यादातर असली metaclass इस्तेमाल सँभालता है, और कभी metaclass conflict नहीं देता।
如果只需要"对每个子类做点什么",优先用 __init_subclass__。它不带任何复杂性就覆盖了大多数实际的元类用途,而且从不引起元类冲突。
5
Prefer a class decorator over a metaclass when the change is for one class, not a whole family. Decorators combine cleanly; metaclasses don't. (Decorators are an upcoming tutorial.)
जब बदलाव पूरे परिवार के लिए नहीं, एक class के लिए हो, तो metaclass की जगह class decorator चुनें। Decorators साफ़ तरह जुड़ते हैं; metaclasses नहीं। (Decorators आने वाले tutorial में।)
如果修改只针对一个类而不是整个家族,优先用 类装饰器 而不是元类。装饰器可以干净地组合,元类不行。(装饰器将在后续教程讲解。)
6
Metaclass conflicts are the most painful metaclass bug. If a class's parents use unrelated metaclasses, Python refuses to build it. Design metaclass families on purpose; don't stack them casually.
Metaclass conflicts metaclasses का सबसे तकलीफ़देह bug हैं। अगर class के parents अलग-अलग metaclasses इस्तेमाल करें, तो Python उसे बनाने से मना करता है। Metaclass families सोच-समझकर बनाइए; लापरवाही से न जोड़िए।
元类冲突 是元类带来的最棘手的 bug。如果一个类的父类使用互不相关的元类,Python 会拒绝创建它。要有意识地设计元类家族,不要随意叠加。
7
Metaclasses cost every reader extra effort — another layer to understand. If your code is not a framework or library, that cost is usually not worth paying.
Metaclasses हर पढ़ने वाले से अतिरिक्त मेहनत माँगते हैं — समझने को एक और परत। अगर आपका code framework या library नहीं, तो यह क़ीमत आमतौर पर चुकाने लायक़ नहीं।
元类会让每位读者多付出努力 — 又多了一层需要理解的东西。如果你的代码不是框架或库,这个代价通常不值得。
8
Convention: use mcs as the first parameter of __new__ (the metaclass), and cls for __init__/__call__ (the class being handled). It is what every experienced Python developer expects.
परंपरा: __new__ का पहला parameter mcs (metaclass) रखें, और __init__/__call__ के लिए cls (जिस class पर काम हो रहा है)। हर अनुभवी Python developer यही उम्मीद करता है।
约定:__new__ 的第一个参数用 mcs(元类),__init__/__call__ 用 cls(正在处理的类)。这是每个有经验的 Python 开发者的预期。
9
When registering subclasses in __init__, check if bases: first — otherwise the base class registers itself too and breaks your lookup table.
__init__ में subclasses register करते समय पहले if bases: जाँचें — वरना base class भी ख़ुद register हो जाती है और आपकी lookup table बिगाड़ देती है।
在 __init__ 中注册子类时,先 检查 if bases: — 否则基类也会注册自己,搞乱你的查找表。
10
When in doubt, ask three questions. Do I need to change the class namespace itself? → metaclass. Do I just want to run code for each subclass? → __init_subclass__. Do I want to change one specific class? → class decorator. Use the simplest tool that works.
शक हो तो तीन सवाल पूछिए। क्या class namespace ही बदलना है? → metaclass। क्या बस हर subclass के लिए code चलाना है? → __init_subclass__। क्या एक ख़ास class बदलनी है? → class decorator। जो सबसे आसान औज़ार काम करे, वही लें।
拿不准时问三个问题。需要修改类的命名空间本身吗?→ 元类。只是想对每个子类运行代码吗?→ __init_subclass__。只想修改某一个类吗?→ 类装饰器。用能解决问题的最简单工具。

Quick Quiz — 8 Questionsछोटा Quiz — 8 सवाल小测验 — 8 道题

🏆 QuizPick an answer to see why.जवाब चुनें और कारण देखें।选一个答案,看看原因。
🎯
Key Takeawayमुख्य सीख关键要点

Classes are objects made by a metaclass — type by default, and type(name, bases, namespace) builds a class by hand. A custom metaclass subclasses type: __new__ shapes the class before it exists, __init__ follows up after, and __call__ runs on every instantiation. For most needs, __init_subclass__ or a class decorator is simpler — keep metaclasses for framework-level work.

Classes metaclass से बने objects हैं — default रूप से type, और type(name, bases, namespace) हाथ से class बनाता है। Custom metaclass type की subclass है: __new__ class बनने से पहले उसे आकार देता है, __init__ बाद का काम करता है, और __call__ हर instance बनाने पर चलता है। ज़्यादातर ज़रूरतों के लिए __init_subclass__ या class decorator आसान है — metaclasses framework-स्तर के काम के लिए रखें।

类是由元类创建的对象 — 默认是 type,而 type(name, bases, namespace) 可以手工创建类。自定义元类继承 type:__new__ 在类存在之前塑造它,__init__ 负责之后的处理,__call__ 在每次实例化时运行。大多数需求用 __init_subclass__ 或类装饰器更简单 — 元类留给框架级别的工作。

🐍 Try Python Yourself

Write, run and visualize Python step by step. No install needed.

You have completed Class and Object. View all sections →