Since type is the default class class of a python class, and a class call creates a new instance of this class, a call type with the correct arguments will result in a new class.
my_class = type("my_class", (object,), {"an_attribute": 1})
Now my_class refers to a new class called "my_class", which is a subclass of object , with the attribute "an_attribute", whose value is 1. Since methods are also just class attributes that point to a function object, you can add them to the attribute dictionary:
{"an_attribute": 1, "a_method": lambda self: print("Hello")}
Here's how it works. I do not recommend doing it this way unless you absolutely need to. In 99% of cases, you do not. See @Parker Coates answer for a clean way to achieve your goal.
Bachsau
source share