ℹ️ 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.2 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.datacamp.com/tutorial/python-metaclasses |
| Last Crawled | 2026-04-05 06:00:32 (5 days ago) |
| First Indexed | 2022-04-16 08:47:23 (3 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Python Meta Class Tutorial with Examples | DataCamp |
| Meta Description | Learn how to implement metaclasses in Python. Find steps in this tutorial to create your own custom meta classes today! |
| Meta Canonical | null |
| Boilerpipe Text | A metaclass in
Python
is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes. Before we dive deeper into metaclasses, let's get a few concepts out of the way.
Everything in Python is an Object
class
TestClass
(
)
:
pass
my_test_class
=
TestClass
(
)
print
(
my_test_class
)
Was this AI assistant helpful?
<
__main__
.
TestClass object at
0x7f6fcc6bf908
>
Was this AI assistant helpful?
Python Classes can be Created Dynamically
type
in Python enables us to find the type of an object. We can proceed to check the type of object we created above.
type
(
TestClass
)
Was this AI assistant helpful?
type
Was this AI assistant helpful?
type
(
type
)
Was this AI assistant helpful?
type
Was this AI assistant helpful?
Wait, What just happened? We'd expect the type of the object we created above to be class, but it's not. Hold on to that thought. We will cover it further in a few. We also notice that the type of
type
itself is
type
. It is an instance of
type
. Another magical thing that
type
does is enable us to create classes dynamically. Let's show how we'd do that below. The
DataCamp
class shown below would be created as shown below using
type
:
class
DataCamp
(
)
:
pass
Was this AI assistant helpful?
DataCampClass
=
type
(
'DataCamp'
,
(
)
,
{
}
)
print
(
DataCampClass
)
print
(
DataCamp
(
)
)
Was this AI assistant helpful?
<
class
'__main__.DataCamp'
>
<
__main__
.
DataCamp object at
0x7f6fcc66e358
>
Was this AI assistant helpful?
In the above example
DataCamp
is the class name while
DataCampClass
is the variable that holds the class reference. When using
type
we can pass attributes of the class using a dictionary as shown below:
PythonClass
=
type
(
'PythonClass'
,
(
)
,
{
'start_date'
:
'August 2018'
,
'instructor'
:
'John Doe'
}
)
print
(
PythonClass
.
start_date
,
PythonClass
.
instructor
)
print
(
PythonClass
)
Was this AI assistant helpful?
August
2018
John Doe
<
class
'__main__.PythonClass'
>
Was this AI assistant helpful?
In case we wanted our
PythonClass
to inherit from the
DataCamp
class we pass it to our second argument when defining the class using
type
PythonClass
=
type
(
'PythonClass'
,
(
DataCamp
,
)
,
{
'start_date'
:
'August 2018'
,
'instructor'
:
'John Doe'
}
)
Was this AI assistant helpful?
print
(
PythonClass
)
Was this AI assistant helpful?
<
class
'__main__.PythonClass'
>
Was this AI assistant helpful?
Now that those two concepts are out of the way, we realize that Python creates the classes using a metaclass. We have seen that everything in Python is an object, these objects are created by metaclasses. Whenever we call
class
to create a class, there is a metaclass that does the magic of creating the class behind the scenes. We've already seen
type
do this in practice above. It is similar to
str
that creates strings and
int
that creates integers. In Python, the
___class__
attribute enables us to check the type of the current instance. Let's create a string below and check its type.
article
=
'metaclasses'
article
.
__class__
Was this AI assistant helpful?
str
Was this AI assistant helpful?
We can also check the type using
type(article)
.
type
(
article
)
Was this AI assistant helpful?
str
Was this AI assistant helpful?
When we check the type of
str
, we also find out that it's type.
type
(
str
)
Was this AI assistant helpful?
type
Was this AI assistant helpful?
When we check the type for
float
,
int
,
list
,
tuple
, and
dict
, we will have a similar output. This is because all of these objects are of type
type
.
print
(
type
(
list
)
,
type
(
float
)
,
type
(
dict
)
,
type
(
tuple
)
)
Was this AI assistant helpful?
<
class
'type'
>
<
class
'type'
>
<
class
'type'
>
<
class
'type'
>
Was this AI assistant helpful?
We've already seen
type
creates classes. Hence when we check the
__class__
of
__class__
it should return
type
.
article
.
__class__
.
__class__
Was this AI assistant helpful?
type
Was this AI assistant helpful?
Master your data skills with DataCamp
More than 10 million people learn Python, R, SQL, and other tech skills using our hands-on courses crafted by industry experts.
In Python, we can customize the class creation process by passing the
metaclass
keyword in the class definition. This can also be done by inheriting a class that has already passed in this keyword.
class
MyMeta
(
type
)
:
pass
class
MyClass
(
metaclass
=
MyMeta
)
:
pass
class
MySubclass
(
MyClass
)
:
pass
Was this AI assistant helpful?
We can see below that the type of
MyMeta
class is
type
and that the type of
MyClass
and
MySubClass
is
MyMeta
.
print
(
type
(
MyMeta
)
)
print
(
type
(
MyClass
)
)
print
(
type
(
MySubclass
)
)
Was this AI assistant helpful?
<
class
'type'
>
<
class
'__main__.MyMeta'
>
<
class
'__main__.MyMeta'
>
Was this AI assistant helpful?
When defining a class and no metaclass is defined the default
type
metaclass will be used. If a metaclass is given and it is not an instance of
type()
, then it is used directly as the metaclass.
Metaclasses can also be defined in one of the two ways shown below. We'll explain the difference between them below.
class
MetaOne
(
type
)
:
def
__new__
(
cls
,
name
,
bases
,
dict
)
:
pass
class
MetaTwo
(
type
)
:
def
__init__
(
self
,
name
,
bases
,
dict
)
:
pass
Was this AI assistant helpful?
__new__
is used when one wants to define dict or bases tuples before the class is created. The return value of
__new__
is usually an instance of
cls
.
__new__
allows subclasses of immutable types to customize instance creation. It can be overridden in custom metaclasses to customize class creation.
__init__
is usually called after the object has been created so as to initialize it.
Metaclass
__call__
method
According to the official
docs
, we can also override other class methods by defining a custom
__call__()
method in the metaclass that allows custom behavior when the class is called.
Metaclass
__prepare__
method
According to Python's
data model docs
Once the appropriate metaclass has been identified, then the class namespace is prepared. If the metaclass has a
__prepare__
attribute, it is called as
namespace = metaclass.__prepare__(name, bases, **kwds)
(where the additional keyword arguments, if any, come from the class definition). If the metaclass has no
__prepare__
attribute, then the class namespace is initialized as an empty ordered mapping.
-
docs.python.org
Singleton Design using a Metaclass
This is a design pattern that restricts the instantiation of a class to only one object. This could prove useful for example when designing a class to connect to the database. One might want to have just one instance of the connection class.
class
SingletonMeta
(
type
)
:
_instances
=
{
}
def
__call__
(
cls
,
*
args
,
**
kwargs
)
:
if
cls
not
in
cls
.
_instances
:
cls
.
_instances
[
cls
]
=
super
(
SingletonMeta
,
cls
)
.
__call__
(
*
args
,
**
kwargs
)
return
cls
.
_instances
[
cls
]
class
SingletonClass
(
metaclass
=
SingletonMeta
)
:
pass
Was this AI assistant helpful?
Conclusion
In this article, we have learned about what metaclasses are and how we can implement them in our Python programming. Metaclasses can be applied in logging, registration of classes at creation time and profiling among others. They seem to be quite abstract concepts, and you might be wondering if you need to use them at all. Long-term Pythonista, Tim Peters answers that question best.
"Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don’t (the people who actually need them know with certainty that they need them, and don’t need an explanation about why).”
-
realpython
If you would like to learn more about Python, start DataCamp's
Python Programming
skill track and check out our
Python Classes Tutorial
.
References
Link one
Link two
Topics |
| Markdown | [ **Master the world’s most popular programming language.** **All levels welcome.** Register for Free](https://events.datacamp.com/ai-powered-python)
[Skip to main content](https://www.datacamp.com/tutorial/python-metaclasses#main)
EN
[English](https://www.datacamp.com/tutorial/python-metaclasses)[Español](https://www.datacamp.com/es/tutorial/python-metaclasses)[Português](https://www.datacamp.com/pt/tutorial/python-metaclasses)[DeutschBeta](https://www.datacamp.com/de/tutorial/python-metaclasses)[FrançaisBeta](https://www.datacamp.com/fr/tutorial/python-metaclasses)[ItalianoBeta](https://www.datacamp.com/it/tutorial/python-metaclasses)[TürkçeBeta](https://www.datacamp.com/tr/tutorial/python-metaclasses)[Bahasa IndonesiaBeta](https://www.datacamp.com/id/tutorial/python-metaclasses)[Tiếng ViệtBeta](https://www.datacamp.com/vi/tutorial/python-metaclasses)[NederlandsBeta](https://www.datacamp.com/nl/tutorial/python-metaclasses)[हिन्दीBeta](https://www.datacamp.com/hi/tutorial/python-metaclasses)[日本語Beta](https://www.datacamp.com/ja/tutorial/python-metaclasses)[한국어Beta](https://www.datacamp.com/ko/tutorial/python-metaclasses)[PolskiBeta](https://www.datacamp.com/pl/tutorial/python-metaclasses)[RomânăBeta](https://www.datacamp.com/ro/tutorial/python-metaclasses)[РусскийBeta](https://www.datacamp.com/ru/tutorial/python-metaclasses)[SvenskaBeta](https://www.datacamp.com/sv/tutorial/python-metaclasses)[ไทยBeta](https://www.datacamp.com/th/tutorial/python-metaclasses)[中文(简体)Beta](https://www.datacamp.com/zh/tutorial/python-metaclasses)
***
[More Information](https://support.datacamp.com/hc/en-us/articles/21821832799255-Languages-Available-on-DataCamp)
[Found an Error?]()
[Log in](https://www.datacamp.com/users/sign_in?redirect=%2Ftutorial%2Fpython-metaclasses)[Get Started](https://www.datacamp.com/users/sign_up?redirect=%2Ftutorial%2Fpython-metaclasses)
Tutorials
[Blogs](https://www.datacamp.com/blog)
[Tutorials](https://www.datacamp.com/tutorial)
[docs](https://www.datacamp.com/doc)
[Podcasts](https://www.datacamp.com/podcast)
[Cheat Sheets](https://www.datacamp.com/cheat-sheet)
[code-alongs](https://www.datacamp.com/code-along)
[Newsletter](https://dcthemedian.substack.com/)
Category
Category
Technologies
Discover content by tools and technology
[AI Agents](https://www.datacamp.com/tutorial/category/ai-agents)[AI News](https://www.datacamp.com/tutorial/category/ai-news)[Artificial Intelligence](https://www.datacamp.com/tutorial/category/ai)[AWS](https://www.datacamp.com/tutorial/category/aws)[Azure](https://www.datacamp.com/tutorial/category/microsoft-azure)[Business Intelligence](https://www.datacamp.com/tutorial/category/learn-business-intelligence)[ChatGPT](https://www.datacamp.com/tutorial/category/chatgpt)[Databricks](https://www.datacamp.com/tutorial/category/databricks)[dbt](https://www.datacamp.com/tutorial/category/dbt)[Docker](https://www.datacamp.com/tutorial/category/docker)[Excel](https://www.datacamp.com/tutorial/category/excel)[Generative AI](https://www.datacamp.com/tutorial/category/generative-ai)[Git](https://www.datacamp.com/tutorial/category/git)[Google Cloud Platform](https://www.datacamp.com/tutorial/category/google-cloud-platform)[Hugging Face](https://www.datacamp.com/tutorial/category/Hugging-Face)[Java](https://www.datacamp.com/tutorial/category/java)[Julia](https://www.datacamp.com/tutorial/category/julia)[Kafka](https://www.datacamp.com/tutorial/category/apache-kafka)[Kubernetes](https://www.datacamp.com/tutorial/category/kubernetes)[Large Language Models](https://www.datacamp.com/tutorial/category/large-language-models)[MongoDB](https://www.datacamp.com/tutorial/category/mongodb)[MySQL](https://www.datacamp.com/tutorial/category/mysql)[NoSQL](https://www.datacamp.com/tutorial/category/nosql)[OpenAI](https://www.datacamp.com/tutorial/category/OpenAI)[PostgreSQL](https://www.datacamp.com/tutorial/category/postgresql)[Power BI](https://www.datacamp.com/tutorial/category/power-bi)[PySpark](https://www.datacamp.com/tutorial/category/pyspark)[Python](https://www.datacamp.com/tutorial/category/python)[R](https://www.datacamp.com/tutorial/category/r-programming)[Scala](https://www.datacamp.com/tutorial/category/scala)[Snowflake](https://www.datacamp.com/tutorial/category/snowflake)[Spreadsheets](https://www.datacamp.com/tutorial/category/spreadsheets)[SQL](https://www.datacamp.com/tutorial/category/sql)[SQLite](https://www.datacamp.com/tutorial/category/sqlite)[Tableau](https://www.datacamp.com/tutorial/category/tableau)
Category
Topics
Discover content by data science topics
[AI for Business](https://www.datacamp.com/tutorial/category/ai-for-business)[Big Data](https://www.datacamp.com/tutorial/category/big-data)[Career Services](https://www.datacamp.com/tutorial/category/career-services)[Cloud](https://www.datacamp.com/tutorial/category/cloud)[Data Analysis](https://www.datacamp.com/tutorial/category/data-analysis)[Data Engineering](https://www.datacamp.com/tutorial/category/data-engineering)[Data Literacy](https://www.datacamp.com/tutorial/category/data-literacy)[Data Science](https://www.datacamp.com/tutorial/category/data-science)[Data Visualization](https://www.datacamp.com/tutorial/category/data-visualization)[DataLab](https://www.datacamp.com/tutorial/category/datalab)[Deep Learning](https://www.datacamp.com/tutorial/category/deep-learning)[Machine Learning](https://www.datacamp.com/tutorial/category/machine-learning)[MLOps](https://www.datacamp.com/tutorial/category/mlops)[Natural Language Processing](https://www.datacamp.com/tutorial/category/natural-language-processing)[Vector Databases](https://www.datacamp.com/tutorial/category/vector-databases)
[Browse Courses](https://www.datacamp.com/courses-all)
category
1. [Home](https://www.datacamp.com/)
2. [Tutorials](https://www.datacamp.com/tutorial)
3. [Python](https://www.datacamp.com/tutorial/category/python)
# Introduction to Python Metaclasses
In this tutorial, learn what metaclasses are, how to implement them in Python, and how to create custom ones.
Contents
Dec 10, 2018 · 6 min read
Contents
- [Everything in Python is an Object](https://www.datacamp.com/tutorial/python-metaclasses#everything-in-python-is-an-object-<code)
- [Python Classes can be Created Dynamically](https://www.datacamp.com/tutorial/python-metaclasses#python-classes-can-be-created-dynamically-<code)
- [Creating Custom Metaclasses](https://www.datacamp.com/tutorial/python-metaclasses#creating-custom-metaclasses-inpyt)
- [\_\_new\_\_ and \_\_init\_\_](https://www.datacamp.com/tutorial/python-metaclasses#__new__-and-__init__-metac)
- [Metaclass \_\_call\_\_ method](https://www.datacamp.com/tutorial/python-metaclasses#metaclass-__call__-method-accor)
- [Metaclass \_\_prepare\_\_ method](https://www.datacamp.com/tutorial/python-metaclasses#metaclass-__prepare__-method-accor)
- [Singleton Design using a Metaclass](https://www.datacamp.com/tutorial/python-metaclasses#singleton-design-using-a-metaclass-thisi)
- [Conclusion](https://www.datacamp.com/tutorial/python-metaclasses#conclusion-inthi)
- [References](https://www.datacamp.com/tutorial/python-metaclasses#references-<ahre)
## Training more people?
Get your team access to the full DataCamp for business platform.
[For Business](https://www.datacamp.com/business)For a bespoke solution [book a demo](https://www.datacamp.com/business/demo-2).
A metaclass in [Python](https://www.datacamp.com/tutorial/python) is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes. Before we dive deeper into metaclasses, let's get a few concepts out of the way.
### Everything in Python is an Object
```
Powered ByWas this AI assistant helpful? Yes No
```
```
<__main__.TestClass object at 0x7f6fcc6bf908>Powered ByWas this AI assistant helpful? Yes No
```
### Python Classes can be Created Dynamically
`type` in Python enables us to find the type of an object. We can proceed to check the type of object we created above.
```
type(TestClass)Powered ByWas this AI assistant helpful? Yes No
```
```
typePowered ByWas this AI assistant helpful? Yes No
```
```
type(type)Powered ByWas this AI assistant helpful? Yes No
```
```
typePowered ByWas this AI assistant helpful? Yes No
```
Wait, What just happened? We'd expect the type of the object we created above to be class, but it's not. Hold on to that thought. We will cover it further in a few. We also notice that the type of `type` itself is `type`. It is an instance of `type`. Another magical thing that `type` does is enable us to create classes dynamically. Let's show how we'd do that below. The `DataCamp` class shown below would be created as shown below using `type`:
```
Powered ByWas this AI assistant helpful? Yes No
```
```
Powered ByWas this AI assistant helpful? Yes No
```
```
Powered ByWas this AI assistant helpful? Yes No
```
In the above example `DataCamp` is the class name while `DataCampClass` is the variable that holds the class reference. When using `type` we can pass attributes of the class using a dictionary as shown below:
```
Powered ByWas this AI assistant helpful? Yes No
```
```
Powered ByWas this AI assistant helpful? Yes No
```
In case we wanted our `PythonClass` to inherit from the `DataCamp` class we pass it to our second argument when defining the class using `type`
```
PythonClass = type('PythonClass', (DataCamp,), {'start_date': 'August 2018', 'instructor': 'John Doe'} )Powered ByWas this AI assistant helpful? Yes No
```
```
print(PythonClass)Powered ByWas this AI assistant helpful? Yes No
```
```
<class '__main__.PythonClass'>Powered ByWas this AI assistant helpful? Yes No
```
Now that those two concepts are out of the way, we realize that Python creates the classes using a metaclass. We have seen that everything in Python is an object, these objects are created by metaclasses. Whenever we call `class` to create a class, there is a metaclass that does the magic of creating the class behind the scenes. We've already seen `type` do this in practice above. It is similar to `str` that creates strings and `int` that creates integers. In Python, the `___class__`attribute enables us to check the type of the current instance. Let's create a string below and check its type.
```
Powered ByWas this AI assistant helpful? Yes No
```
```
strPowered ByWas this AI assistant helpful? Yes No
```
We can also check the type using `type(article)`.
```
type(article)Powered ByWas this AI assistant helpful? Yes No
```
```
strPowered ByWas this AI assistant helpful? Yes No
```
When we check the type of `str`, we also find out that it's type.
```
type(str)Powered ByWas this AI assistant helpful? Yes No
```
```
typePowered ByWas this AI assistant helpful? Yes No
```
When we check the type for `float`, `int`, `list`, `tuple`, and `dict`, we will have a similar output. This is because all of these objects are of type `type`.
```
print(type(list),type(float), type(dict), type(tuple))Powered ByWas this AI assistant helpful? Yes No
```
```
<class 'type'> <class 'type'> <class 'type'> <class 'type'>Powered ByWas this AI assistant helpful? Yes No
```
We've already seen `type` creates classes. Hence when we check the `__class__` of `__class__` it should return `type`.
```
article.__class__.__class__Powered ByWas this AI assistant helpful? Yes No
```
```
typePowered ByWas this AI assistant helpful? Yes No
```
## Master your data skills with DataCamp
More than 10 million people learn Python, R, SQL, and other tech skills using our hands-on courses crafted by industry experts.
[Start Learning](https://www.datacamp.com/courses-all)

## Creating Custom Metaclasses
In Python, we can customize the class creation process by passing the `metaclass` keyword in the class definition. This can also be done by inheriting a class that has already passed in this keyword.
```
Powered ByWas this AI assistant helpful? Yes No
```
We can see below that the type of `MyMeta` class is `type` and that the type of `MyClass` and `MySubClass` is `MyMeta`.
```
Powered ByWas this AI assistant helpful? Yes No
```
```
Powered ByWas this AI assistant helpful? Yes No
```
When defining a class and no metaclass is defined the default `type` metaclass will be used. If a metaclass is given and it is not an instance of `type()`, then it is used directly as the metaclass.
## `__new__` and `__init__`
Metaclasses can also be defined in one of the two ways shown below. We'll explain the difference between them below.
```
Powered ByWas this AI assistant helpful? Yes No
```
`__new__` is used when one wants to define dict or bases tuples before the class is created. The return value of `__new__`is usually an instance of `cls`. `__new__` allows subclasses of immutable types to customize instance creation. It can be overridden in custom metaclasses to customize class creation. `__init__` is usually called after the object has been created so as to initialize it.
### Metaclass `__call__` method
According to the official [docs](https://docs.python.org/3/reference/datamodel.html), we can also override other class methods by defining a custom `__call__()` method in the metaclass that allows custom behavior when the class is called.
### Metaclass `__prepare__` method
According to Python's [data model docs](https://docs.python.org/3/reference/datamodel.html)
*Once the appropriate metaclass has been identified, then the class namespace is prepared. If the metaclass has a `__prepare__` attribute, it is called as `namespace = metaclass.__prepare__(name, bases, **kwds)` (where the additional keyword arguments, if any, come from the class definition). If the metaclass has no `__prepare__`attribute, then the class namespace is initialized as an empty ordered mapping.* - [docs.python.org](https://docs.python.org/3/reference/datamodel.html?highlight=__setattr__)
### Singleton Design using a Metaclass
This is a design pattern that restricts the instantiation of a class to only one object. This could prove useful for example when designing a class to connect to the database. One might want to have just one instance of the connection class.
```
Powered ByWas this AI assistant helpful? Yes No
```
## Conclusion
In this article, we have learned about what metaclasses are and how we can implement them in our Python programming. Metaclasses can be applied in logging, registration of classes at creation time and profiling among others. They seem to be quite abstract concepts, and you might be wondering if you need to use them at all. Long-term Pythonista, Tim Peters answers that question best.
*"Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don’t (the people who actually need them know with certainty that they need them, and don’t need an explanation about why).”* - [realpython](https://realpython.com/python-metaclasses)
If you would like to learn more about Python, start DataCamp's [Python Programming](https://www.datacamp.com/tracks/python-programming) skill track and check out our [Python Classes Tutorial](https://www.datacamp.com/tutorial/python-classes).
### References
[Link one](https://www.python.org/dev/peps/pep-3115)
[Link two](https://docs.python.org/3/reference/datamodel.html#metaclasses)
Topics
[Python](https://www.datacamp.com/tutorial/category/python)
***
[Derrick Mwiti](https://www.datacamp.com/portfolio/mwitiderrick)
***
Topics
[Python](https://www.datacamp.com/tutorial/category/python)
[Inner Classes in Python](https://www.datacamp.com/tutorial/inner-classes-python)
[Python Descriptors Tutorial](https://www.datacamp.com/tutorial/python-descriptors)
[Python Data Classes: A Comprehensive Tutorial](https://www.datacamp.com/tutorial/python-data-classes)
[How to Use Python Decorators (With Function and Class-Based Examples)](https://www.datacamp.com/tutorial/decorators-python)
[Python Classes Tutorial](https://www.datacamp.com/tutorial/python-classes)
[Object-Oriented Programming in Python: A Complete Guide](https://www.datacamp.com/tutorial/python-oop-tutorial)
Python Courses
Course
### [Introduction to Python](https://www.datacamp.com/courses/intro-to-python-for-data-science)
4 hr
6\.8M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
[See Details](https://www.datacamp.com/courses/intro-to-python-for-data-science)
[Start Course](https://www.datacamp.com/users/sign_up?redirect=%2Fcourses%2Fintro-to-python-for-data-science%2Fcontinue)
Course
### [Intermediate Python](https://www.datacamp.com/courses/intermediate-python)
4 hr
1\.3M
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.
[See Details](https://www.datacamp.com/courses/intermediate-python)
[Start Course](https://www.datacamp.com/users/sign_up?redirect=%2Fcourses%2Fintermediate-python%2Fcontinue)
Course
### [Introduction to Data Science in Python](https://www.datacamp.com/courses/introduction-to-data-science-in-python)
4 hr
495\.8K
Dive into data science using Python and learn how to effectively analyze and visualize your data. No coding experience or skills needed.
[See Details](https://www.datacamp.com/courses/introduction-to-data-science-in-python)
[Start Course](https://www.datacamp.com/users/sign_up?redirect=%2Fcourses%2Fintroduction-to-data-science-in-python%2Fcontinue)
[See More](https://www.datacamp.com/category/python)
Related
[TutorialInner Classes in Python](https://www.datacamp.com/tutorial/inner-classes-python)
In this basic Python tutorial, you'll learn about why and when you should use inner classes.
Hafeezul Kareem Shaik
[TutorialPython Descriptors Tutorial](https://www.datacamp.com/tutorial/python-descriptors)
Learn what Python Descriptors are, when you should use them, and why you should use them.
Aditya Sharma
[TutorialPython Data Classes: A Comprehensive Tutorial](https://www.datacamp.com/tutorial/python-data-classes)
A beginner-friendly tutorial on Python data classes and how to use them in practice
Bex Tuychiev
[TutorialHow to Use Python Decorators (With Function and Class-Based Examples)](https://www.datacamp.com/tutorial/decorators-python)
Learn Python decorators with hands-on examples. Understand closures, function and class-based decorators, and how to write reusable, elegant code.
[](https://www.datacamp.com/portfolio/mwitiderrick)
Derrick Mwiti
[TutorialPython Classes Tutorial](https://www.datacamp.com/tutorial/python-classes)
In Python, everything is an object. Numbers, strings, DataFrames, even functions are objects. In particular, everything you deal with in Python has a class, a blueprint associated with it under the hood.
DataCamp Team
[TutorialObject-Oriented Programming in Python: A Complete Guide](https://www.datacamp.com/tutorial/python-oop-tutorial)
Learn the fundamentals of object-oriented programming in Python, including classes, objects, inheritance, encapsulation, and polymorphism.
[](https://www.datacamp.com/portfolio/theov)
Théo Vanderheyden
[See More](https://www.datacamp.com/tutorial/category/python)
[See More](https://www.datacamp.com/tutorial/category/python)
## Grow your data skills with DataCamp for Mobile
Make progress on the go with our mobile courses and daily 5-minute coding challenges.
[Download on the App Store](https://datacamp.onelink.me/xztQ/45dozwue?deep_link_sub1=%7B%22src_url%22%3A%22https%3A%2F%2Fwww.datacamp.com%2Ftutorial%2Fpython-metaclasses%22%7D)[Get it on Google Play](https://datacamp.onelink.me/xztQ/go2f19ij?deep_link_sub1=%7B%22src_url%22%3A%22https%3A%2F%2Fwww.datacamp.com%2Ftutorial%2Fpython-metaclasses%22%7D)
**Learn**
[Learn Python](https://www.datacamp.com/blog/how-to-learn-python-expert-guide)[Learn AI](https://www.datacamp.com/blog/how-to-learn-ai)[Learn Power BI](https://www.datacamp.com/learn/power-bi)[Learn Data Engineering](https://www.datacamp.com/category/data-engineering)[Assessments](https://www.datacamp.com/signal)[Career Tracks](https://www.datacamp.com/tracks/career)[Skill Tracks](https://www.datacamp.com/tracks/skill)[Courses](https://www.datacamp.com/courses-all)[Data Science Roadmap](https://www.datacamp.com/blog/data-science-roadmap)
**Data Courses**
[Python Courses](https://www.datacamp.com/category/python)[R Courses](https://www.datacamp.com/category/r)[SQL Courses](https://www.datacamp.com/category/sql)[Power BI Courses](https://www.datacamp.com/category/power-bi)[Tableau Courses](https://www.datacamp.com/category/tableau)[Alteryx Courses](https://www.datacamp.com/category/alteryx)[Azure Courses](https://www.datacamp.com/category/azure)[AWS Courses](https://www.datacamp.com/category/aws)[Google Cloud Courses](https://www.datacamp.com/category/google-cloud)[Google Sheets Courses](https://www.datacamp.com/category/google-sheets)[Excel Courses](https://www.datacamp.com/category/excel)[AI Courses](https://www.datacamp.com/category/artificial-intelligence)[Data Analysis Courses](https://www.datacamp.com/category/data-analysis)[Data Visualization Courses](https://www.datacamp.com/category/data-visualization)[Machine Learning Courses](https://www.datacamp.com/category/machine-learning)[Data Engineering Courses](https://www.datacamp.com/category/data-engineering)[Probability & Statistics Courses](https://www.datacamp.com/category/probability-and-statistics)
**DataLab**
[Get Started](https://www.datacamp.com/datalab)[Pricing](https://www.datacamp.com/datalab/pricing)[Security](https://www.datacamp.com/datalab/security)[Documentation](https://datalab-docs.datacamp.com/)
**Certification**
[Certifications](https://www.datacamp.com/certification)[Data Scientist](https://www.datacamp.com/certification/data-scientist)[Data Analyst](https://www.datacamp.com/certification/data-analyst)[Data Engineer](https://www.datacamp.com/certification/data-engineer)[SQL Associate](https://www.datacamp.com/certification/sql-associate)[Power BI Data Analyst](https://www.datacamp.com/certification/data-analyst-in-power-bi)[Tableau Certified Data Analyst](https://www.datacamp.com/certification/data-analyst-in-tableau)[Azure Fundamentals](https://www.datacamp.com/certification/azure-fundamentals)[AI Fundamentals](https://www.datacamp.com/certification/ai-fundamentals)
**Resources**
[Resource Center](https://www.datacamp.com/resources)[Upcoming Events](https://www.datacamp.com/webinars)[Blog](https://www.datacamp.com/blog)[Code-Alongs](https://www.datacamp.com/code-along)[Tutorials](https://www.datacamp.com/tutorial)[Docs](https://www.datacamp.com/doc)[Open Source](https://www.datacamp.com/open-source)[RDocumentation](https://www.rdocumentation.org/)[Book a Demo with DataCamp for Business](https://www.datacamp.com/business/demo)[Data Portfolio](https://www.datacamp.com/data-portfolio)
**Plans**
[Pricing](https://www.datacamp.com/pricing)[For Students](https://www.datacamp.com/pricing/student)[For Business](https://www.datacamp.com/business)[For Universities](https://www.datacamp.com/universities)[Discounts, Promos & Sales](https://www.datacamp.com/promo)[Expense DataCamp](https://www.datacamp.com/expense)[DataCamp Donates](https://www.datacamp.com/donates)
**For Business**
[Business Pricing](https://www.datacamp.com/business/compare-plans)[Teams Plan](https://www.datacamp.com/business/learn-teams)[Data & AI Unlimited Plan](https://www.datacamp.com/business/data-unlimited)[Customer Stories](https://www.datacamp.com/business/customer-stories)[Partner Program](https://www.datacamp.com/business/partner-program)
**About**
[About Us](https://www.datacamp.com/about)[Learner Stories](https://www.datacamp.com/stories)[Careers](https://www.datacamp.com/careers)[Become an Instructor](https://www.datacamp.com/learn/create)[Press](https://www.datacamp.com/press)[Leadership](https://www.datacamp.com/about/leadership)[Contact Us](https://support.datacamp.com/hc/en-us/articles/360021185634)[DataCamp Español](https://www.datacamp.com/es)[DataCamp Português](https://www.datacamp.com/pt)[DataCamp Deutsch](https://www.datacamp.com/de)[DataCamp Français](https://www.datacamp.com/fr)
**Support**
[Help Center](https://support.datacamp.com/hc/en-us)[Become an Affiliate](https://www.datacamp.com/affiliates)
[Facebook](https://www.facebook.com/datacampinc/)
[Twitter](https://twitter.com/datacamp)
[LinkedIn](https://www.linkedin.com/school/datacampinc/)
[YouTube](https://www.youtube.com/channel/UC79Gv3mYp6zKiSwYemEik9A)
[Instagram](https://www.instagram.com/datacamp/)
[Privacy Policy](https://www.datacamp.com/privacy-policy)[Cookie Notice](https://www.datacamp.com/cookie-notice)[Do Not Sell My Personal Information](https://www.datacamp.com/do-not-sell-my-personal-information)[Accessibility](https://www.datacamp.com/accessibility)[Security](https://www.datacamp.com/security)[Terms of Use](https://www.datacamp.com/terms-of-use)
© 2026 DataCamp, Inc. All Rights Reserved. |
| Readable Markdown | A metaclass in [Python](https://www.datacamp.com/tutorial/python) is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes. Before we dive deeper into metaclasses, let's get a few concepts out of the way. Everything in Python is an Object Python Classes can be Created Dynamically `type` in Python enables us to find the type of an object. We can proceed to check the type of object we created above. Wait, What just happened? We'd expect the type of the object we created above to be class, but it's not. Hold on to that thought. We will cover it further in a few. We also notice that the type of `type` itself is `type`. It is an instance of `type`. Another magical thing that `type` does is enable us to create classes dynamically. Let's show how we'd do that below. The `DataCamp` class shown below would be created as shown below using `type`: In the above example `DataCamp` is the class name while `DataCampClass` is the variable that holds the class reference. When using `type` we can pass attributes of the class using a dictionary as shown below: In case we wanted our `PythonClass` to inherit from the `DataCamp` class we pass it to our second argument when defining the class using `type` Now that those two concepts are out of the way, we realize that Python creates the classes using a metaclass. We have seen that everything in Python is an object, these objects are created by metaclasses. Whenever we call `class` to create a class, there is a metaclass that does the magic of creating the class behind the scenes. We've already seen `type` do this in practice above. It is similar to `str` that creates strings and `int` that creates integers. In Python, the `___class__`attribute enables us to check the type of the current instance. Let's create a string below and check its type. We can also check the type using `type(article)`. When we check the type of `str`, we also find out that it's type. When we check the type for `float`, `int`, `list`, `tuple`, and `dict`, we will have a similar output. This is because all of these objects are of type `type`. We've already seen `type` creates classes. Hence when we check the `__class__` of `__class__` it should return `type`.
## Master your data skills with DataCamp
More than 10 million people learn Python, R, SQL, and other tech skills using our hands-on courses crafted by industry experts.

In Python, we can customize the class creation process by passing the `metaclass` keyword in the class definition. This can also be done by inheriting a class that has already passed in this keyword. We can see below that the type of `MyMeta` class is `type` and that the type of `MyClass` and `MySubClass` is `MyMeta`. When defining a class and no metaclass is defined the default `type` metaclass will be used. If a metaclass is given and it is not an instance of `type()`, then it is used directly as the metaclass. Metaclasses can also be defined in one of the two ways shown below. We'll explain the difference between them below. `__new__` is used when one wants to define dict or bases tuples before the class is created. The return value of `__new__`is usually an instance of `cls`. `__new__` allows subclasses of immutable types to customize instance creation. It can be overridden in custom metaclasses to customize class creation. `__init__` is usually called after the object has been created so as to initialize it. Metaclass `__call__` method According to the official [docs](https://docs.python.org/3/reference/datamodel.html), we can also override other class methods by defining a custom `__call__()` method in the metaclass that allows custom behavior when the class is called. Metaclass `__prepare__` method According to Python's [data model docs](https://docs.python.org/3/reference/datamodel.html) *Once the appropriate metaclass has been identified, then the class namespace is prepared. If the metaclass has a `__prepare__` attribute, it is called as `namespace = metaclass.__prepare__(name, bases, **kwds)` (where the additional keyword arguments, if any, come from the class definition). If the metaclass has no `__prepare__`attribute, then the class namespace is initialized as an empty ordered mapping.* - [docs.python.org](https://docs.python.org/3/reference/datamodel.html?highlight=__setattr__) Singleton Design using a Metaclass This is a design pattern that restricts the instantiation of a class to only one object. This could prove useful for example when designing a class to connect to the database. One might want to have just one instance of the connection class. Conclusion In this article, we have learned about what metaclasses are and how we can implement them in our Python programming. Metaclasses can be applied in logging, registration of classes at creation time and profiling among others. They seem to be quite abstract concepts, and you might be wondering if you need to use them at all. Long-term Pythonista, Tim Peters answers that question best. *"Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don’t (the people who actually need them know with certainty that they need them, and don’t need an explanation about why).”* - [realpython](https://realpython.com/python-metaclasses) If you would like to learn more about Python, start DataCamp's [Python Programming](https://www.datacamp.com/tracks/python-programming) skill track and check out our [Python Classes Tutorial](https://www.datacamp.com/tutorial/python-classes). References [Link one](https://www.python.org/dev/peps/pep-3115) [Link two](https://docs.python.org/3/reference/datamodel.html#metaclasses)
Topics |
| Shard | 136 (laksa) |
| Root Hash | 7979813049800185936 |
| Unparsed URL | com,datacamp!www,/tutorial/python-metaclasses s443 |