Suppose I have a library with something like the following, where Person
is a user-facing class.
class SwissArmyKnife:
def open_bottle(self):
"""...etc...."""
def open_package_with_scissors(self):
"""...etc...."""
def uncork_wine(self):
"""...etc...."""
def whittle_an_intricate_dolphin_figurine(self):
"""...etc...."""
class Person:
def __init__(self):
self.swiss_army_knife = SwissArmyKnife()
def open_bottle(self):
self.swiss_army_knife.open_bottle()
def open_package_with_scissors(self):
self.swiss_army_knife.open_package_with_scissors()
def uncork_wine(self):
self.swiss_army_knife.uncork_wine()
def whittle_an_intricate_dolphin_figurine(self):
self.swiss_army_knife.whittle_an_intricate_dolphin_figurine()
I want to pass along all of the methods of SwissArmyKnife
to Person
, since the Person
will have a SwissArmyKnife
, but ideally, I'd like to avoid all of the boilerplate code in the Person
class, since every time I update what a swiss army knife can do, I'd have to remember to update the person class as well.
One way of doing this would be to have Person
inherit from SwissArmyKnife
, but that feels pretty awkward, since a person isn't a swiss army knife; they just have one.
Another possibility would be just to expect users to write person.swiss_army_knife.open_bottle()
, but that's a little verbose. Also, in the actual case that's leading me to ask this toy question, I've already released a version of my library in which you can just write person.open_bottle()
and I don't want to break backwards compatibility.
Is there a good way that I'm not seeing to autopopulate the methods of SwissArmyKnife
to Person
? What's the pythonic thing to do?