Back
+15 XP
Concept

Type is a Class, Class is an Object

In Python, classes are objects too! `type(name, bases, dict)` creates brand-new classes dynamically at runtime without typing a `class` statement 🧬.

python
# Dynamic class creation: type(name, bases, dict)
Dog = type("Dog", (), {"species": "Canine", "bark": lambda self: "Woof! 🐶"})

d = Dog()
print(type(d))        # <class '__main__.Dog'> 🧬
print(d.species)      # 'Canine'
print(d.bark())       # 'Woof! 🐶'

# 61. Type is a Class, Class is an Object In Python, classes are objects too! `type(name, bases, dict)` creates brand-new classes dynamically at runtime without typing a `class` statement 🧬. ```python # Dynamic class creation: type(name, bases, dict) Dog = type("Dog", (), {"species": "Canine", "bark": lambda self: "Woof! 🐶"}) d = Dog() print(type(d)) # <class '__main__.Dog'> 🧬 print(d.species) # 'Canine' print(d.bark()) # 'Woof! 🐶' ``` When you write `class Foo:`, Python executes the body and passes the resulting namespace to `type(...)`. `type` is the metaclass that constructs all classes! 🧬 --- ### Question What are the three arguments passed to `type()` when creating a class dynamically? 🧠 - [ ] a. Class name string, tuple of base classes, and attribute dictionary 🧬 - [ ] b. File path, line number, and function signature - [ ] c. Memory address, thread ID, and process handle - [ ] d. Module name, export list, and docstring --- ### Challenge Use `type()` to dynamically create class `Robot` with attribute `power = 100`. Instantiate it and print `Robot().power`. 🎯 <details> <summary>Solution</summary> ```python Robot = type("Robot", (), {"power": 100}) bot = Robot() print(bot.power) ``` </details>

Checkpoint

What are the three arguments passed to `type()` when creating a class dynamically? 🧠

Practice

Use `type()` to dynamically create class `Robot` with attribute `power = 100`. Instantiate it and print `Robot().power`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks