šŸ•·ļø Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 103 (from laksa059)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ā„¹ļø Skipped - page is already crawled

šŸ“„
INDEXABLE
āœ…
CRAWLED
19 days ago
šŸ¤–
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.7 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://www.geeksforgeeks.org/python/python-metaclasses/
Last Crawled2026-03-18 15:52:14 (19 days ago)
First Indexed2025-06-13 02:21:21 (9 months ago)
HTTP Status Code200
Meta TitlePython Meta Classes - GeeksforGeeks
Meta DescriptionYour All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more., Your All-in-One Learning Portal. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
Meta Canonicalnull
Boilerpipe Text
Last Updated : 17 Feb, 2026 A metaclass in Python is a class that defines how other classes are created and behave. Just like objects are created from classes, classes themselves are created from metaclasses. In short: Class → creates objects Metaclass → creates classes By default, Python uses the built-in metaclass "type" to create all classes. Steps to Create a Metaclass Define a metaclass: Create a class that inherits from type. Optionally, define __new__ or __init__ to customize class creation. Use the metaclass in a class: Specify metaclass=YourMeta when defining a class. Class is created by the metaclass: The metaclass can modify attributes or methods of the class automatically. Create instances of the class: Instances work normally, the metaclass only affects the class itself. Output Hello from Person! Explanation: Meta(type): Defines a metaclass that can modify classes when they are created. __new__: Adds a greet method automatically to any class using this metaclass. Person(metaclass=Meta): Class created using the metaclass, so it gets the greet method. p = Person("Olivia"): Creates an instance of Person. p.greet(): Calls the method injected by the metaclass. Creating Subclass Subclasses can also be created dynamically using type. Output Vegetarian {'Bitter Guard', 'Spinach'} Explanation: VegType inherits from FoodType dynamically. vegFoods method is added via the attributes dictionary. Metaclasses can be inherited just like normal classes. When a class inherits from a metaclass, it becomes an instance of that metaclass. Output <class '__main__.MetaCls'> <class 'type'> <class '__main__.MetaCls'> Explanation: A is created by MetaCls -> type is MetaCls B is normal -> type is type C inherits from A -> type is MetaCls A class cannot inherit from two different metaclasses. Python will raise a TypeError. Error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Explanation: Python allows only one metaclass per class. 'C' inherits from two different metaclasses → conflict occurs. Metaclasses are useful when you want to control class creation or enforce rules. 1. Class Verification: This example shows how a metaclass can enforce rules on class attributes. Explanation: Ensures a class cannot have both foo and bar attributes. Useful for interface enforcement. 2. Prevent Subclass Inheritance: This example shows how a metaclass can treat abstract classes differently, preventing certain checks for them while enforcing rules on normal classes. Output Abstract Class: AbsCls Normal Class: NormCls Explanation: Abstract classes can skip metaclass checks. Normal classes are validated by the metaclass. Dynamic Generation of Classes Dynamic class generation allows you to create classes at runtime instead of defining them statically in code.
Markdown
[![geeksforgeeks](https://media.geeksforgeeks.org/gfg-gg-logo.svg)](https://www.geeksforgeeks.org/) ![search icon](https://media.geeksforgeeks.org/auth-dashboard-uploads/Property=Light---Default.svg) - Sign In - [Courses]() - [Tutorials]() - [Interview Prep]() - [Python Tutorial](https://www.geeksforgeeks.org/python/python-programming-language-tutorial/) - [Data Types](https://www.geeksforgeeks.org/python/python-data-types/) - [Interview Questions](https://www.geeksforgeeks.org/python/python-interview-questions/) - [Examples](https://www.geeksforgeeks.org/python/python-programming-examples/) - [Quizzes](https://www.geeksforgeeks.org/python/python-quizzes/) - [DSA Python](https://www.geeksforgeeks.org/dsa/python-data-structures-and-algorithms/) - [Data Science](https://www.geeksforgeeks.org/data-science/data-science-with-python-tutorial/) - [NumPy](https://www.geeksforgeeks.org/python/numpy-tutorial/) - [Pandas](https://www.geeksforgeeks.org/pandas/pandas-tutorial/) - [Practice](https://www.geeksforgeeks.org/dsa/geeksforgeeks-practice-best-online-coding-platform/) # Python Meta Classes Last Updated : 17 Feb, 2026 A metaclass in Python is a class that defines how other classes are created and behave. Just like objects are created from classes, classes themselves are created from metaclasses. In short: - Class → creates objects - Metaclass → creates classes By default, Python uses the built-in metaclass ****"type"**** to create all classes. ## Steps to Create a Metaclass 1. ****Define a metaclass:**** Create a class that inherits from type. Optionally, define \_\_new\_\_ or \_\_init\_\_ to customize class creation. 2. ****Use the metaclass in a class:**** Specify metaclass=YourMeta when defining a class. 3. ****Class is created by the metaclass:**** The metaclass can modify attributes or methods of the class automatically. 4. ****Create instances of the class:**** Instances work normally, the metaclass only affects the class itself. Python `` ``` class Meta(type): ``` ``` def __new__(cls, name, bases, dct): ``` ``` dct['greet'] = lambda self: f"Hello from {name}!" ``` ``` return super().__new__(cls, name, bases, dct) ``` ``` ​ ``` ``` class Person(metaclass=Meta): ``` ``` def __init__(self, name): ``` ``` self.name = name ``` ``` ​ ``` ``` p = Person("Olivia") ``` ``` ​ ``` ``` print(p.greet()) ``` **Output** ``` Hello from Person! ``` ****Explanation:**** - ****Meta(type):**** Defines a metaclass that can modify classes when they are created. - ****\_\_new\_\_:**** Adds a greet method automatically to any class using this metaclass. - ****Person(metaclass=Meta):**** Class created using the metaclass, so it gets the greet method. - ****p = Person("Olivia"):**** Creates an instance of Person. - ****p.greet():**** Calls the method injected by the metaclass. ## Creating Subclass Subclasses can also be created dynamically using type. Python `` ``` def init(self, ftype): ``` ``` self.ftype = ftype ``` ``` ​ ``` ``` def getFtype(self): ``` ``` return self.ftype ``` ``` ​ ``` ``` FoodType = type('FoodType', (object,), { ``` ``` '__init__': init, ``` ``` 'getFtype': getFtype ``` ``` }) ``` ``` ​ ``` ``` def vegFoods(self): ``` ``` return {'Spinach', 'Bitter Guard'} ``` ``` ​ ``` ``` VegType = type('VegType', (FoodType,), { ``` ``` 'vegFoods': vegFoods ``` ``` }) ``` ``` ​ ``` ``` v = VegType("Vegetarian") ``` ``` print(v.getFtype()) ``` ``` print(v.vegFoods()) ``` **Output** ``` Vegetarian {'Bitter Guard', 'Spinach'} ``` ****Explanation:**** - VegType inherits from FoodType dynamically. - vegFoods method is added via the attributes dictionary. ## Metaclass Inheritance Metaclasses can be inherited just like normal classes. When a class inherits from a metaclass, it becomes an instance of that metaclass. Python `` ``` class MetaCls(type): ``` ``` pass ``` ``` ​ ``` ``` A = MetaCls('A', (object,), {}) ``` ``` class B(object): ``` ``` pass ``` ``` class C(A, B): ``` ``` pass ``` ``` ​ ``` ``` print(type(A)) ``` ``` print(type(B)) ``` ``` print(type(C)) ``` **Output** ``` <class '__main__.MetaCls'> <class 'type'> <class '__main__.MetaCls'> ``` ****Explanation:**** - A is created by MetaCls -\> type is MetaCls - B is normal -\> type is type - C inherits from A -\> type is MetaCls ## Metaclass Conflicts A class cannot inherit from two different metaclasses. Python will raise a TypeError. Python `` ``` class MetaCls(type): ``` ``` pass ``` ``` ​ ``` ``` A = MetaCls('A', (object,), {}) ``` ``` print("Type of A:", type(A)) ``` ``` ​ ``` ``` class B(object): ``` ``` pass ``` ``` print("Type of B:", type(B)) ``` ``` ​ ``` ``` class C(A, B): ``` ``` pass ``` ``` ​ ``` ``` print("Type of C:", type(C)) ``` ### Error: > TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases ****Explanation:**** - Python allows only one metaclass per class. - 'C' inherits from two different metaclasses → conflict occurs. ## Metaclass Use Cases Metaclasses are useful when you want to control class creation or enforce rules. ****1\. Class Verification:**** This example shows how a metaclass can enforce rules on class attributes. Python `` ``` class MainClass(type): ``` ``` def __new__(cls, name, bases, attrs): ``` ``` if 'foo' in attrs and 'bar' in attrs: ``` ``` raise TypeError(f"Class {name} cannot have both foo and bar") ``` ``` return super().__new__(cls, name, bases, attrs) ``` ``` ​ ``` ``` # This will raise an error ``` ``` class SubClass(metaclass=MainClass): ``` ``` foo = 42 ``` ``` bar = 34 ``` ****Explanation:**** - Ensures a class cannot have both foo and bar attributes. - Useful for interface enforcement. ****2\. Prevent Subclass Inheritance:**** This example shows how a metaclass can treat abstract classes differently, preventing certain checks for them while enforcing rules on normal classes. Python `` ``` class MetaCls(type): ``` ``` def __new__(cls, name, bases, attrs): ``` ``` if attrs.pop('abstract', False): ``` ``` print('Abstract Class:', name) ``` ``` return super().__new__(cls, name, bases, attrs) ``` ``` print('Normal Class:', name) ``` ``` return super().__new__(cls, name, bases, attrs) ``` ``` ​ ``` ``` class AbsCls(metaclass=MetaCls): ``` ``` abstract = True ``` ``` ​ ``` ``` class NormCls(metaclass=MetaCls): ``` ``` foo = 42 ``` **Output** ``` Abstract Class: AbsCls Normal Class: NormCls ``` ****Explanation:**** - Abstract classes can skip metaclass checks. - Normal classes are validated by the metaclass. ## Dynamic Generation of Classes Dynamic class generation allows you to create classes at runtime instead of defining them statically in code. Python `` ``` class FoodType: ``` ``` events = [] ``` ``` ​ ``` ``` def __init__(self, ftype, items): ``` ``` self.ftype = ftype ``` ``` self.items = items ``` ``` FoodType.events.append(self) ``` ``` ​ ``` ``` def run(self): ``` ``` print("Food Type:", self.ftype) ``` ``` print("Food Menu:", self.items) ``` ``` ​ ``` ``` @staticmethod ``` ``` def run_events(): ``` ``` for e in FoodType.events: ``` ``` e.run() ``` ``` ​ ``` ``` def sub_food(ftype): ``` ``` class_name = ftype.capitalize() ``` ``` def __init__(self, items): ``` ``` FoodType.__init__(self, ftype, items) ``` ``` globals()[class_name] = type(class_name, (FoodType,), {'__init__': __init__}) ``` ``` ​ ``` ``` # Create dynamic classes ``` ``` [ sub_food(ftype) for ftype in ["Vegetarian", "Nonvegetarian"] ] ``` ``` ​ ``` ``` Vegetarian(['Spinach', 'Bitter Guard']) ``` ``` Nonvegetarian(['Meat', 'Fish']) ``` ``` FoodType.run_events() ``` **Output** ``` Food Type: Vegetarian Food Menu: ['Spinach', 'Bitter Guard'] Food Type: Nonvegetarian Food Menu: ['Meat', 'Fish'] ``` ****Explanation:**** - sub\_food dynamically creates subclasses of FoodType. - Each subclass can be instantiated and used like normal classes. ### Related Articles: > - [Python Metaclass \_\_new\_\_() Method](https://www.geeksforgeeks.org/python/python-metaclass-__new__-method/) > - [Metaprogramming with Metaclasses in Python](https://www.geeksforgeeks.org/python/metaprogramming-metaclasses-python/) Comment [S](https://www.geeksforgeeks.org/user/sonugeorge/) [sonugeorge](https://www.geeksforgeeks.org/user/sonugeorge/) Follow 7 Article Tags: Article Tags: [Python](https://www.geeksforgeeks.org/category/programming-language/python/) [python-oop-concepts](https://www.geeksforgeeks.org/tag/python-oop-concepts/) ### Explore [![GeeksforGeeks](https://media.geeksforgeeks.org/auth-dashboard-uploads/gfgFooterLogo.png)](https://www.geeksforgeeks.org/) ![location](https://media.geeksforgeeks.org/img-practice/Location-1685004904.svg) Corporate & Communications Address: A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305) ![location](https://media.geeksforgeeks.org/img-practice/Location-1685004904.svg) Registered Address: K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305 [![GFG App on Play Store](https://media.geeksforgeeks.org/auth-dashboard-uploads/googleplay-%281%29.png)](https://geeksforgeeksapp.page.link/gfg-app)[![GFG App on App Store](https://media.geeksforgeeks.org/auth-dashboard-uploads/appstore-%281%29.png)](https://geeksforgeeksapp.page.link/gfg-app) - Company - [About Us](https://www.geeksforgeeks.org/about/) - [Legal](https://www.geeksforgeeks.org/legal/) - [Privacy Policy](https://www.geeksforgeeks.org/legal/privacy-policy/) - [Contact Us](https://www.geeksforgeeks.org/about/contact-us/) - [Advertise with us](https://www.geeksforgeeks.org/advertise-with-us/) - [GFG Corporate Solution](https://www.geeksforgeeks.org/gfg-corporate-solution/) - [Campus Training Program](https://www.geeksforgeeks.org/campus-training-program/) - Explore - [POTD](https://www.geeksforgeeks.org/problem-of-the-day) - [Job-A-Thon](https://practice.geeksforgeeks.org/events/rec/job-a-thon/) - [Blogs](https://www.geeksforgeeks.org/category/blogs/?type=recent) - [Nation Skill Up](https://www.geeksforgeeks.org/nation-skill-up/) - Tutorials - [Programming Languages](https://www.geeksforgeeks.org/computer-science-fundamentals/programming-language-tutorials/) - [DSA](https://www.geeksforgeeks.org/dsa/dsa-tutorial-learn-data-structures-and-algorithms/) - [Web Technology](https://www.geeksforgeeks.org/web-tech/web-technology/) - [AI, ML & Data Science](https://www.geeksforgeeks.org/machine-learning/ai-ml-and-data-science-tutorial-learn-ai-ml-and-data-science/) - [DevOps](https://www.geeksforgeeks.org/devops/devops-tutorial/) - [CS Core Subjects](https://www.geeksforgeeks.org/gate/gate-exam-tutorial/) - [Interview Preparation](https://www.geeksforgeeks.org/aptitude/interview-corner/) - [Software and Tools](https://www.geeksforgeeks.org/websites-apps/software-and-tools-a-to-z-list/) - Courses - [ML and Data Science](https://www.geeksforgeeks.org/courses/category/machine-learning-data-science) - [DSA and Placements](https://www.geeksforgeeks.org/courses/category/dsa-placements) - [Web Development](https://www.geeksforgeeks.org/courses/category/development-testing) - [Programming Languages](https://www.geeksforgeeks.org/courses/category/programming-languages) - [DevOps & Cloud](https://www.geeksforgeeks.org/courses/category/cloud-devops) - [GATE](https://www.geeksforgeeks.org/courses/category/gate) - [Trending Technologies](https://www.geeksforgeeks.org/courses/category/trending-technologies/) - Videos - [DSA](https://www.geeksforgeeks.org/videos/category/sde-sheet/) - [Python](https://www.geeksforgeeks.org/videos/category/python/) - [Java](https://www.geeksforgeeks.org/videos/category/java-w6y5f4/) - [C++](https://www.geeksforgeeks.org/videos/category/c/) - [Web Development](https://www.geeksforgeeks.org/videos/category/web-development/) - [Data Science](https://www.geeksforgeeks.org/videos/category/data-science/) - [CS Subjects](https://www.geeksforgeeks.org/videos/category/cs-subjects/) - Preparation Corner - [Interview Corner](https://www.geeksforgeeks.org/interview-prep/interview-corner/) - [Aptitude](https://www.geeksforgeeks.org/aptitude/aptitude-questions-and-answers/) - [Puzzles](https://www.geeksforgeeks.org/aptitude/puzzles/) - [GfG 160](https://www.geeksforgeeks.org/courses/gfg-160-series) - [System Design](https://www.geeksforgeeks.org/system-design/system-design-tutorial/) [@GeeksforGeeks, Sanchhaya Education Private Limited](https://www.geeksforgeeks.org/), [All rights reserved](https://www.geeksforgeeks.org/copyright-information/) ![]()
Readable Markdown
Last Updated : 17 Feb, 2026 A metaclass in Python is a class that defines how other classes are created and behave. Just like objects are created from classes, classes themselves are created from metaclasses. In short: - Class → creates objects - Metaclass → creates classes By default, Python uses the built-in metaclass ****"type"**** to create all classes. ## Steps to Create a Metaclass 1. ****Define a metaclass:**** Create a class that inherits from type. Optionally, define \_\_new\_\_ or \_\_init\_\_ to customize class creation. 2. ****Use the metaclass in a class:**** Specify metaclass=YourMeta when defining a class. 3. ****Class is created by the metaclass:**** The metaclass can modify attributes or methods of the class automatically. 4. ****Create instances of the class:**** Instances work normally, the metaclass only affects the class itself. **Output** ``` Hello from Person! ``` ****Explanation:**** - ****Meta(type):**** Defines a metaclass that can modify classes when they are created. - ****\_\_new\_\_:**** Adds a greet method automatically to any class using this metaclass. - ****Person(metaclass=Meta):**** Class created using the metaclass, so it gets the greet method. - ****p = Person("Olivia"):**** Creates an instance of Person. - ****p.greet():**** Calls the method injected by the metaclass. ## Creating Subclass Subclasses can also be created dynamically using type. **Output** ``` Vegetarian {'Bitter Guard', 'Spinach'} ``` ****Explanation:**** - VegType inherits from FoodType dynamically. - vegFoods method is added via the attributes dictionary. Metaclasses can be inherited just like normal classes. When a class inherits from a metaclass, it becomes an instance of that metaclass. **Output** ``` <class '__main__.MetaCls'> <class 'type'> <class '__main__.MetaCls'> ``` ****Explanation:**** - A is created by MetaCls -\> type is MetaCls - B is normal -\> type is type - C inherits from A -\> type is MetaCls A class cannot inherit from two different metaclasses. Python will raise a TypeError. ### Error: > TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases ****Explanation:**** - Python allows only one metaclass per class. - 'C' inherits from two different metaclasses → conflict occurs. Metaclasses are useful when you want to control class creation or enforce rules. ****1\. Class Verification:**** This example shows how a metaclass can enforce rules on class attributes. ****Explanation:**** - Ensures a class cannot have both foo and bar attributes. - Useful for interface enforcement. ****2\. Prevent Subclass Inheritance:**** This example shows how a metaclass can treat abstract classes differently, preventing certain checks for them while enforcing rules on normal classes. **Output** ``` Abstract Class: AbsCls Normal Class: NormCls ``` ****Explanation:**** - Abstract classes can skip metaclass checks. - Normal classes are validated by the metaclass. ## Dynamic Generation of Classes Dynamic class generation allows you to create classes at runtime instead of defining them statically in code.
Shard103 (laksa)
Root Hash12046344915360636903
Unparsed URLorg,geeksforgeeks!www,/python/python-metaclasses/ s443