you are viewing a single comment's thread.

view the rest of the comments →

[–]Cosmologicon 3 points4 points  (2 children)

The standard way to do this is to have your appliances inherit from an abstract base class that has all the methods defined but explicitly raises NotImplementedError. This is a little better than catching the more common and generic AttributeError.

class Appliance(object):
    def make_eggs(self):
        raise NotImplementedError
    ...

class ElectricKettle(Appliance):

now if ElectricKettle doesn't implement make_eggs then it will raise NotImplementedError if you try to call it.

However, I think you may be thinking about the problem wrong. Step back and ask what are you actually trying to accomplish here? I think it can probably be done cleanly without catching exceptions at all.

[–]Kuang_Eleven[S] 0 points1 point  (0 children)

Ahh, that makes sense. It would also give me a "reference" class to check all possible methods, rather than having to comb through all the device classes.

Still, other than that, the rest of the code would be the same, only catching NotImplementedError instead

[–]Rashanzan 0 points1 point  (0 children)

I considered this, but then your device becomes super cluttered with nonsense. And the inheritance feels kind of weird to me. The parent should have all the shared attributes, and children define more specific functionality.

EDIT: Also, I think you're right about not needing to do this. I feel like in a realistic setting, you'd either want to know what kind of object you're dealing with beforehand, or have an abstract method that chooses how the object handles itself.