creating a similar object from an derived class
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Wed Sep 3 14:01:32 EDT 2008
Scott a écrit :
> Let's say I have an object:
s/object/class/
> 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
classmethod:
class Foo(object):
@classmethod
def create_another(cls):
return cls()
HTH
More information about the Python-list
mailing list