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

Rhodri James rhodri at wildebst.demon.co.uk
Fri Oct 30 00:33:03 CET 2009


On Thu, 29 Oct 2009 22:45:45 -0000, metal <metal29a at gmail.com> wrote:

> Consider the following:

[fixed to actually inherit...]

> ########################################
> class Parent:
> 	def some_method(self):
> 		return Parent(...)
> class Child(Parent):
> 	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(Parent):
> 	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?

That's a perfectly good way to do it.  If __class__ really
offends you that much, wrap it in another (probably static)
method:

class Parent(object):
   def some_method(self):
     return self.another_one(...)

   @staticmethod
   def another_one(...):
     return Parent(...)

class Child(Parent):
   def some_method(self):
     return Parent.some_method(self)

   @staticmethod
   def another_one(...):
     return Child(...)

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list