[issue44090] Add class binding to unbound super objects for allowing autosuper with class methods
Géry
report at bugs.python.org
Wed Mar 23 13:22:45 EDT 2022
Géry <gery.ogam at gmail.com> added the comment:
Apologies for the long delay.
> Do we have any meaningful examples to show that this is desired and useful?
A use case of `super()` in a `classmethod` that comes to mind is for parameterized factory methods. It is a variation of the classic factory method design pattern that lets the factory method of a creator creates *multiple* products according to a parameter identifying the product to create. Overriding the factory method lets you change or extend the products that are created, by mapping existing identifiers to different products or introducing new identifiers for new products (cf. GoF’s book *Design Patterns*, section ‘Factory Method’, subsection ‘Implementation’, paragraph 2):
```
>>> class MyCreator:
... @classmethod
... def make(cls, product_id):
... if product_id == 'mine': return MyProduct(creator=cls)
... if product_id == 'yours': return YourProduct(creator=cls)
... if product_id == 'theirs': return TheirProduct(creator=cls)
... raise ValueError('product_id {!r} not supported'.format(product_id))
...
>>> class YourCreator(MyCreator):
... @classmethod
... def make(cls, product_id):
... if product_id == 'mine': return YourProduct(creator=cls)
... if product_id == 'yours': return MyProduct(creator=cls)
... return super(YourCreator, cls).make(product_id)
...
>>> class BaseProduct:
... def __init__(self, creator): self._creator = creator
... def __repr__(self):
... return '{}(creator={})'.format(
... type(self).__name__, self._creator.__name__)
...
>>> class MyProduct(BaseProduct): pass
...
>>> class YourProduct(BaseProduct): pass
...
>>> class TheirProduct(BaseProduct): pass
...
>>> MyCreator.make('mine')
MyProduct(creator=MyCreator)
>>> YourCreator.make('mine')
YourProduct(creator=YourCreator)
```
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44090>
_______________________________________
More information about the Python-bugs-list
mailing list