Reputation: 46430
If you have a setup like this:
class Animal(object):
@staticmethod
def create():
return Animal()
class Frog(Animal):
pass
You can create animals like Animal.create()
but if you do Frog.create()
you also get an Animal
and not a Frog
. Is there a way to change the create()
method to make it create an instance of the class it's being called from?
Upvotes: 0
Views: 149
Reputation: 155670
This is a typical use case for classmethod
:
class Animal(object):
@classmethod
def create(cls):
return cls()
class Frog(Animal):
pass
>>> Animal.create()
<Animal object at 0x51fc190>
>>> Frog.create()
<Frog object at 0x51fc610>
Upvotes: 3