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

Dave Angel davea at ieee.org
Fri Oct 30 00:50:05 CET 2009


metal wrote:
> Consider the following:
>
> ########################################
> class Parent:
> 	def some_method(self):
> 		return Parent(...)
> class Child:
> 	def some_method(self):
> 		...
> 		return Parent.some_method(self)
> ########################################
>
> Or Simply:
>
> ########################################
> class Parent:
> 	def some_method(self):
> 		return Parent(...)
> class Child:
> 	pass
> ########################################
>
> Child().some_method() returns a Parent instance.
>
> 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?
>
>
>   
You need to do a few things here. 
1) tell us what version of Python you're targeting, and whether these 
are old-style or new-style classes you're trying to define.

2) Actually show the class declaration completely.  Currently you don't 
show the (object) or the (Parent) base class declarations.

3) Explain what the desired goal is.  Using a phrase like "rewrite 
Parent like this to avoid that" implies that I already know what 
particular "that" has you bothered.

4) If you post multiple similar code blocks, label them somehow, so we 
have a way to refer to them unambiguously.

With my present guesses, the definition of some_method() in the third 
declaration of Child would seem to be redundant.

DaveA




More information about the Python-list mailing list