我假設你擁有所有這些的父類,或至少一個mixin。把一個默認的返回函數放在父類或mixin中,然後在不同的類中重載它......這是唯一正確的方法。
當然,它使額外的代碼,但至少它的封裝和可擴展性。假設你想增加對另外五個班級的支持。不要在那裏修改代碼,只需將正確的代碼添加到新類中即可。從外觀上看,每班有兩條線(功能定義和返回線)。這並不壞,是嗎?
如果obj
不包含返回功能,那麼將引發異常,你能趕上並用乾淨的良心忽視的一類。
class MyMixin:
def my_return(self, *args):
return self.name
... possibly other things...
class SomeClass(MyMixin):
... no alteration to the default ...
class AnotherClass(MyParent, MyMixin):
def my_return(self, *args):
return args[0].normalize(self.identifier)
... blabla
# now, this is in the caller object...
try:
rval = obj.my_return(self) # this is the caller object 'self', not the 'self' in the 'obj'
#dosomething with rval
except Exception:
pass #no rval for this object type, skipping it...
請不要。這是實現多態的可怕方式。 – 2010-02-28 15:43:48