5.16. OOP Class Creation

5.16.1. Class Definition

>>> class MyClass:
...     pass
>>> MyClass = type('MyClass', (), {})

5.16.2. Class Attributes

>>> class MyClass:
...     myattr = 1
>>> MyClass = type('MyClass', (), {'myattr': 1})

5.16.3. Class Methods

>>> class MyClass:
...     def mymethod(self):
...         pass
>>> def mymethod(self):
...     pass
>>>
>>> MyClass = type('MyClass', (), {'mymethod': mymethod})

5.16.4. Class Inheritance

>>> class Parent:
...     pass
>>>
>>>
>>> class MyClass(Parent):
...     pass
>>> MyClass = type('MyClass', (Parent,), {})

5.16.5. Recap

>>> class Parent:
...     pass
>>>
>>>
>>> class MyClass(Parent):
...     myattr = 1
...
...     def mymethod(self):
...         pass
>>> MyClass = type('MyClass', (Parent,), {'myattr': 1, 'mymethod': mymethod})

5.16.6. Use Case - Dynamic Class Creation

>>> for classname in ['Astronaut', 'Cosmonaut', 'Taikonaut']:
...     globals()[classname] = type(classname, (), {})