classical.subclass module
Tools for creating subclasses
- classical.subclass.argumented_subclass(cls: type, name: str, *args, **kwargs)[source]
Create a subclass of
cls
identical to the original except for its name and additional arguments passed to__init__
- Parameters
cls – the class to be subclassed
name – name of the new class
args – positional arguments for
__init__
kwargs – keyword arguments for
__init__
- Returns
a subclass of
cls
Say you have
class Square: def __init__(self, size, color=None): pass # implementation goes here
The ‘standard’ way to subclass with fixed argument values would be to
class RedSquare1x1(Square): def __init__(self): super().__init__(1, color='red)
Consider the less-verbose alternative (kind of like the
partial
function, but for classes):RedSquare1x1 = argumented_subclass(Square, 'RedSquare1x1', 1, color='red')
Note
Existence of
__slots__
(and, consequently, the absence of the instance__dict__
) is preserved during subclassing
- classical.subclass.attributed_subclass(cls: type, name: str, **attributes)[source]
Create a subclass of
cls
identical to the original, but with additional or redefined attributes- Parameters
cls – the class to be subclassed
name – name of the new class
attributes – new attributes
- Returns
a subclass of
cls
class Animal: pass # implementation goes here Bird = attributed_subclass(Animal, 'Bird', wings=2) pelican = Bird() # pelican.wings == 2
Note
Existence of
__slots__
(and, consequently, the absence of the instance__dict__
) is preserved during subclassing