creating a similar object from an derived class

Bruno Desthuilliers bdesth.quelquechose at
Wed Sep 3 20:01:32 CEST 2008

Scott a écrit :
> Let's say I have an object:


> class foo():
>    def create_another()
>        return foo()

class Foo(object):
     def create_another(self):
         return Foo()

>    def blah():

      def blah(self):
>        x = self.create_another()
>        ... do something with X

> Now I create a inherited class of this object:
> class bar(foo):

class Bar(Foo):
>     ...
> If I call bar.create_another(), it will

Actually, it will raise a TypeError...

> return a foo() instead of a
> bar(). This isn't what I want. I would like bar.create_another() to
> create an instance for bar().

    def create_another(self)
        return type(self)()

And while you're at it, since - at least in this concrete case - you 
need access to the class but not to the instance, you could make it a 

class Foo(object):
     def create_another(cls):
         return cls()


More information about the Python-list mailing list