inheritance - Creating a Java-like interface in Python -
i have multiple classes have common functionality, implemented differently various reasons. i'm using these classes in same context, don't know 1 used until run time. want instantiate different classes, use the same line of code invoke common functionality.
so, i've though of using inheritance (obviously), , code looks 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 able instantiate of derived classes base (so don't have make special case , checks every new class add) , call it's common
method , desired "a" or "b" result.
python dynamically typed language duck typing. unlike statically typed languages java, there no need have interfaces. if have object, can call any method of in way want. interpreter try find such method , call , worst can happen exception @ run time. that’s how dynamically typed languages work.
with duck typing, having methods want in object, can expect object of type expect be. there no need check inheritance of it.
so in case, can rid of base
(unless of course want provide default implementation). , object call obj.common()
. if want on safe side, can check if method exists first:
if hasattr(obj, 'common'): obj.common()
alternatively, if keep base type around, check inheritance if want:
if isinstance(obj, base): obj.common()
but in general, call method , check if works: it’s easier ask forgiveness permission. this:
try: obj.common() except attributeerror: print('oops, object wasn’t right after all')
Comments
Post a Comment