type()
- Python course
- Expert
- Lesson 1/47
- 5 min
Learn dynamic class creation with type().
Dynamic classes with type()
With one argument type() returns an object's type. With three arguments it creates a new class: type(name, bases, dict).
Here name is the class name, bases is a tuple of parent classes and dict is the namespace of attributes and methods. The result works like a class written with class. This lets you build structure from data; for example you can generate classes from a settings file.
The dict argument
The third argument — the dict — defines the class namespace. Entries like "x": 0 become instance attributes, entries like "show": lambda self: ... become methods.
The first parameter of a method is self. You can also add __init__ to the dict; then the dynamic class gets a constructor. This flexibility lets you build at runtime anything you could write with a class statement.
Practice Build the Point class with type()
Build the Point class with type(). The second argument is the empty tuple (), the third is a dict. The dict should have x and y attributes (value 0) and a show method. show returns f"{self.x},{self.y}". Create an instance, set x=3 and y=4, then print show().
Starter code
# Build the Point class dynamically
# add x, y attributes and a show method
# then print the instanceSample solution
# Build the Point class dynamically
Point = type("Point", (), {
"x": 0,
"y": 0,
"show": lambda self: f"{self.x},{self.y}",
})
p = Point()
p.x = 3
p.y = 4
print(p.show())Expected output
3,4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does type("X", (), {}) return?
cls = type("X", (), {})- It raises an error
- An empty object
- A new class object Correct answer
- The type object itself
Explanation: type with three arguments creates and returns a new class.
2 Complete the type() call
Point = type("Point", (), {____, "y": 0})
Point = type("Point", (), {"x": 0, "y": 0})
Explanation: The dict entry is the key-value pair "x": 0.
3 Match type() concepts
| Term | Meaning |
|---|---|
type |
Creates a class |
isim |
Class name |
tabanlar |
Base class tuple |
sözlük |
Attribute map |