creating a similar object from an derived class

MRAB google at mrabarnett.plus.com
Wed Sep 3 18:29:43 EDT 2008


On Sep 3, 8:09 pm, Scott <smba... at gmail.com> wrote:
> Let's say I have an object:
>
> class foo():
>    def create_another()
>        return foo()
>
>    def blah():
>        x = self.create_another()
>        ... do something with X
>
> Now I create a inherited class of this object:
>
> class bar(foo):
>     ...
>
> If I call bar.create_another(), it will 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(). Obviously I can do this by overriding
> create_another, i.e.
>
> class bar(foo):
>     def create_another()
>         return bar()
>
> However, is there a way for me to modify foo() so that it
> automatically creates objects of the derived class, so that I don't
> have to continue to redefine create_another() ?
>
> For example, I tried the following:
>
> def create_another()
>     return self.type()()
>
> but it did not work.
>
If you want a foo object to be able to create another foo object and a
bar object to be able to create another bar object then you could do
this:

    class foo():
        def create_another(self):
            return self.__class__()

    class bar(foo):
        pass



More information about the Python-list mailing list