About
With the three arguments of the type function, you can create dynamically a new class (ie a type object).
type is a class that creates class objects
type.__class__
<class 'type'>
Articles Related
Syntax
class type(name, bases, dict)
where:
- name is the class name and becomes the __name__ attribute
- bases is a tuple of the parent classes for inheritance (can be empty). It becomes the __bases__ attribute;
- dict is a dictionary that define the attributes of the class. It becomes the __dict__ attribute.
class MyMinimalClass(object):
pass
type('MyMinimalClass', (), {})
Management
Create Attribute (variable, function)
The following two statements from the doc create two identical type objects with two attributes:
- one as a variable
- an other as function
This code:
class X(object):
a = 1;
def echo(self):
print(self.a)
is identical with the below one.
def echo_a(self):
print(self.a)
X = type('X', (object,), dict(a=1,echo_a=echo_a))
# or
X = type('X', (object,), { 'a':1, 'echo_a': echo_a } )
Create a class form a parent (Inheritance)
FooChild = type('FooChild', (Foo,), {})
where:
- Foo is the parent class
- FooChild is the child class