[Python-ideas] Keyword for direct pass through of kwargs to super
Michael Lohmann
mial.lohmann at gmail.com
Sat May 26 09:09:50 EDT 2018
> Right, which means that Pizza and Lasagna are not compatible classes
> in that way.
Okay, let me try it one final time with the original pizza example. Let’s assume that your restaurant has a special offer on all Hawaiian Pizzas where you can get all sizes for 10$. Now the only reasonable thing to pass into **kw is size, so let’s say that for the readability of the class we decide to replace it.
class Pizza:
def __init__(self, *, size, price):
print("The price of this %s pizza is:", (size, price))
class HawaiianPizza(Pizza):
def __init__(self, *, pineapple="chunked", size=8): # No **kw here since no longer needed
print("This pizza has %s pineapple." % pineapple)
super().__init__(price=10, size=size)
class CheesyCrust(Pizza):
"""Mixin to alter the pizza's crust"""
def __init__(self, *, crust_cheese="cheddar", surcharge=1.50):
print("Surcharge %.2f for %s crust" % (surcharge, crust_cheese))
super().__init__(price=kw.pop("price") + surcharge, **kw)
class BestPizza(HawaiianPizza, CheesyCrust):
"""Actually, the best pizza is pepperoni. Debate away!"""
BestPizza(crust_cheese="gouda“) # Doesn’t work since Hawaii doesn’t bypass it
But now the HawaiianPizza gets annoyed because it doesn’t know what to do with the crust_cheese. So just to make BestPizza work I will have to add **kw to HawaiianPizza again.
But now let’s say we have a hungry programmer that just takes a short look and sees that HawaiianPizza is a subclass of Pizza and he thinks "Okay then, just get some HawaiianPizza(price=8)". In fact if he directly orders any HawaiianPizza there is nothing he can pass in into **kw that wouldn’t result in an error.
I am sorry to annoy you all with this. Maybe this problem just isn’t as common as I thought it was…
Michael
More information about the Python-ideas
mailing list