As a contrived example, suppose I create a random fruit basket in python. I create a basket:
basket = FruitBasket()
Now I want to indicate specific combinations of fruits that may occur in the basket. Suppose Iām a very picky dude, and the basket should be full of apples and pomegranates, oranges and grapefruits, or just bananas.
I read about overloading the python operator, and it looks like I could define __or__ and __and__ to get the behavior I want. I think I could do something like this:
basket.fruits = (Apple() & Pomegranate()) | (Banana()) | (Orange() & Grapefruit())
This works great by making two classes ( Or and And ). When __or__ or __and__ , I simply return a new Or or And object:
def __or__(self, other): return Or(self, other) def __and__(self, other): return And(self, other)
What I'm trying to understand is how to do this without creating the first results? Why can't I use the static __or__ method in the Fruit base class? I tried this, but it does not work:
class Fruit(object): @classmethod def __or__(self, other): return Or(self, other)
and fetal appropriation:
basket.fruits = (Apple & Pomegranate) | (Orange & Grapefruit) | (Banana)
I get an error message:
TypeError: unsupported operand type(s) for |: 'type' and 'type'
Any thoughts on how to make this work?