Reputation: 5565
I have multiple classes that have common functionality, which is implemented differently for various reasons. I'm using all these classes in the same context, but I don't know which one will be used until run time. I want to instantiate different classes, but use the same line of code to invoke the common functionality.
So, I've though of using inheritance (obviously), and now my code looks like this:
class Base():
def common(self):
return "abstract"
class A(Base):
def common(self):
return "A"
class B(Base):
def common(self):
return "B"
I want to be able to instantiate any of the derived classes as Base (so that I don't have to make a special case and checks for every new class I add) and call it's common
method and get the desired "A" or "B" result.
Upvotes: 0
Views: 1960
Reputation: 387755
Python is a dynamically typed language with duck typing. Unlike statically typed languages like Java, there is no need to have interfaces. If you have an object, you can just call any method of it in any way you want. The interpreter will try to find such a method and call it and the worst that can happen is that you get an exception at run time. That’s how dynamically typed languages work.
With duck typing, just having the methods you want in an object, you can expect the object to be of a type you expect it to be. There is no need to check the inheritance of it.
So in your case, you can even get rid of Base
(unless you of course want to provide a default implementation). And then you just get an object an call obj.common()
. If you want to be on the very safe side, you can also check if the method exists first:
if hasattr(obj, 'common'):
obj.common()
Alternatively, if you keep your base type around, you could also do the check for inheritance if you want:
if isinstance(obj, Base):
obj.common()
But in general, you would just call the method and check if it works: It’s easier to ask for forgiveness than permission. So you would do this:
try:
obj.common()
except AttributeError:
print('Oops, object wasn’t right after all')
Upvotes: 5