简体   繁体   中英

Pattern for subtyping unrelated but similarly-shaped classes in python

I have two classes that have identical shape but don't share a parent class:

class Panda(object):
  def has_thumb(self):
    return True

class Monkey(object):
  def has_thumb(self):
    return True

I would like to subclass each of these to add some functionality:

class TalkingPanda(Panda):
  def has_thumb(self):
    print("I have a thumb")
    return super().has_thumb()

class TalkingMonkey(Monkey):
  def has_thumb(self):
    print("I have a thumb")
    return super().has_thumb()

Is there a way to refactor this code to remove the code duplication?

Sure, since you are using super() already you can use a mixin for this:

class TalkingAnimal:
  def has_thumb(self):
    print("I have a thumb")
    return super().has_thumb()

class TalkingPanda(TalkingAnimal, Panda):
  pass

class TalkingMonkey(TalkingAnimal, Monkey):
  pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM