Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call Python method if it exists

How to call a subclass method from a base class method, only if the subclass supports that method? And what's the best way to do that? Illustrative example, I have an animal that protects my house: if someone walks by it will look angry, and it will bark if it can.

Example code:

class Protector(object):
    def protect(self):
        self.lookangry()
        if hasattr(self, 'bark'):
            self.bark()

class GermanShepherd(Protector):
    def lookangry(self):
        print u') _ _ __/°°¬'
    def bark(self):
        print 'wau wau'

class ScaryCat(Protector):
    def lookangry(self):
        print '=^..^='

I can think of lots of alternative implementations for this:

  1. Using hasattr as above.
  2. try: self.bark() except AttributeError: pass but that also catches any AttributeErrors in bark
  3. Same as 2 but inspect the error message to make sure it's the right AttributeError
  4. Like 2 but define an abstract bark method that raises NotImplementedError in the abstract class and check for NotImplementedError instead of AttributeError. With this solution Pylint will complain that I forgot to override the abstract method in ScaryCat.
  5. Define an empty bark method in the abstract class:

    class Protector(object):
        def protect(self):
            self.lookangry()
            self.bark()
        def bark(self):
            pass
    

I figured in Python their should usually be one way to do something. In this case it's not clear to me which. Which one of these options is most readable, least likely to introduce a bug when stuff is changed and most inline with coding standards, especially Pylint? Is there a better way to do it that I've missed?

like image 435
Joooeey Avatar asked Oct 15 '25 04:10

Joooeey


2 Answers

It seems to me you're thinking about inheritance incorrectly. The base class is supposed to encapsulate everything that is shared across any of the subclasses. If something is not shared by all subclasses, by definition it is not part of the base class.

So your statement "if someone walks by it will look angry, and it will bark if it can" doesn't make sense to me. The "bark if it can" part is not shared across all subclasses, therefore it shouldn't be implemented in the base class.

What should happen is that the subclass that you want to bark adds this functionality to the protect() method. As in:

class Protector():
    def protect(self):
        self.lookangry()

class GermanShepherd(Protector):
    def protect(self):
        super().protect() # or super(GermanShepherd, self).protect() for Python 2
        self.bark()

This way all subclasses will lookangry(), but the subclasses which implement a bark() method will have it as part of the extended functionality of the superclass's protect() method.

like image 179
bnaecker Avatar answered Oct 17 '25 19:10

bnaecker


I think 6.) could be that the Protector class makes just the basic shared methods abstract thus required, while leaving the extra methods to its heirs. Of course this can be splitted into more sub-classes, see https://repl.it/repls/AridScrawnyCoderesource (Written in Python 3.6)

class Protector(object):
  def lookangry(self):
    raise NotImplementedError("If it can't look angry, it can't protect")

  def protect(self):
      self.lookangry()


class Doggo(Protector):
  def bark(self):
    raise NotImplementedError("If a dog can't bark, it can't protect")

  def protect(self):
    super().protect()
    self.bark()


class GermanShepherd(Doggo):

  def lookangry(self):
    print(') _ _ __/°°¬')

  def bark(self):
    print('wau wau')


class Pug(Doggo):
  # We will not consider that screeching as barking so no bark method
  def lookangry(self):
    print('(◉ω◉)')


class ScaryCat(Protector):
  def lookangry(self):
      print('o(≧o≦)o')


class Kitten(Protector):
  pass


doggo = GermanShepherd()
doggo.protect()

try:
  gleam_of_silver = Pug()
  gleam_of_silver.protect()
except NotImplementedError as e:
  print(e)

cheezburger = ScaryCat()
cheezburger.protect()

try:
  ball_of_wool = Kitten()
  ball_of_wool.protect()
except NotImplementedError as e:
  print(e)
like image 24
wiesion Avatar answered Oct 17 '25 18:10

wiesion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!