If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Oct 30 04:51:25 EDT 2009


metal a écrit :
> Consider the following:
> 
(snip)
> class Parent:
> 	def some_method(self):
> 		return Parent(...)
> class Child:
> 	pass
> 
> Child().some_method() returns a Parent instance.

It actually raises an AttributeError. You forgot to make Child inherit 
from Parent.


> We can rewrite Parent like this to avoid that
> 
> ########################################
> class Parent:
> 	def some_method(self):
> 		return self.__class__(...)
> class Child:
> 	def some_method(self):
> 		...
> 		return Parent.some_method(self)
> ########################################
> 
> But this style makes code full with ugly  self.__class__
> 
> Any standard/pythonic way out there?

Others already gave you the appropriate answer (if appliable, of 
course), which is to make some_method a classmethod, or, if some_method 
needs to stay an instancemethod, to factor out the creation of a new 
instance to a classmethod.

Now if it's the self.__class__ that hurts you, you can as well replace 
it with type(self) - assuming you make Parent a new-style class (which 
FWIW is the sensible thing to do anyway).



More information about the Python-list mailing list