Arthur Conmy
Arthur Conmy

Reputation: 13

Better way to pass default arguments to subclasses

Suppose I have some class which I subclass, that has some default (perhaps a flag-like) argument. What's the best way to handle passing such an argument around? I can think of doing

class Dog():
    def __init__(self, noisy = False):
        self.noisy = noisy

    def bark(self):
        if self.noisy:
            print('YAP')
        else:
            print('yap')

class Beagle(Dog):
    def __init__(self, noisy = False):
       super().__init__(noisy)
    
dave = Beagle(noisy = True)
dave.bark()

But this uses noisy seven times, and I feel there must be a better way.

Upvotes: 1

Views: 637

Answers (1)

Marco Bonelli
Marco Bonelli

Reputation: 69276

First of all, you can drop the noisy = in the instantiation of Beagle(), it's unneeded:

dave = Beagle(True)

Secondly, given your implementation, your Beagle class has no reason to exist. It does not add any functionality and does not specialize Dog in any way. If anything, possible subclasses of Dog that make sense would be:

class NoisyDog(Dog):
    def __init__(self):
       super().__init__(True)

class QuietDog(Dog):
    def __init__(self):
       super().__init__(False)

You could also keep the noisy= in the calls to super().__init__() for better readability, but again that's unneeded.

Other than that, there isn't really much else you can do. If you need a class property, you'll have to assign it to the class (self.foo = bar) and then reference it using its name...

Upvotes: 1

Related Questions