ā¹ļø Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.7 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://www.geeksforgeeks.org/python/python-metaclasses/ |
| Last Crawled | 2026-03-18 15:52:14 (19 days ago) |
| First Indexed | 2025-06-13 02:21:21 (9 months ago) |
| HTTP Status Code | 200 |
| Meta Title | Python Meta Classes - GeeksforGeeks |
| Meta Description | Your 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 Canonical | null |
| 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 | [](https://www.geeksforgeeks.org/)

- 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
[](https://www.geeksforgeeks.org/)

Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)

Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
[](https://geeksforgeeksapp.page.link/gfg-app)[](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. |
| Shard | 103 (laksa) |
| Root Hash | 12046344915360636903 |
| Unparsed URL | org,geeksforgeeks!www,/python/python-metaclasses/ s443 |