Curriculum
In Python, the type
class is a built-in class that represents the type of an object. It can be used to create new classes, just like the class
keyword.
The type
class is also known as a metaclass, as it is the class that defines the behavior of other classes. By default, all Python classes are instances of the type
class.
Here’s an example of how the type
class can be used to create a new class:
def speak(self): print("Hello, my name is", self.name) Person = type('Person', (object,), {'speak': speak}) person = Person() person.name = "Alice" person.speak()
In this example, we define a function speak
that prints a message to the console. We then use the type
class to create a new class Person
. The first argument to type
is the name of the new class, the second argument is a tuple containing the base classes of the new class, and the third argument is a dictionary containing the attributes of the new class.
We pass (object,)
as the base class, which means that Person
inherits from the object
class. We also define a single method speak
in the dictionary, which becomes an attribute of the new class.
We then create an instance of the Person
class, set the name
attribute, and call the speak
method.
The output of the above code will be:
Hello, my name is Alice
As you can see, we were able to create a new class Person
dynamically using the type
class. The type
class allows us to define new classes without using the class
keyword, which can be useful in certain situations where we want to create classes programmatically.