samedi 7 mars 2020

Is it pythonic to add a dunder method to a class at run-time (based on the arguments passed to some method)?

When working with subplots in matplotlib, I noticed that one of the objects returned by the subplots method is either subscript-able or not based on the arguments to this method.

f1, axarr1 = plt.subplots(1, 1, sharex='col', sharey='row', figsize=(10, 8))
print(hasattr(axarr1,'__getitem__')) #False
f2, axarr2 = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(10, 8))
print(hasattr(axarr2,'__getitem__')) #True

Although not relevant to the problem I had in mind, it raised the question whether this is the conventional way to add behavior to Python classes.

Aucun commentaire:

Enregistrer un commentaire