我假设你拥有所有这些的父类,或至少一个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