Ole Kristian
Ole Kristian

Reputation: 61

Make a method that create an object of its own class

Let's say I create a class "Animal" and make a child class "Cow", is it possible to make a method in "Animal" that I can call from the class "Cow" and that will generate a class of itself? For example:

 class Animal:
    def __init__(self, identity, food, water):
      self.identity = identity
      self.food = food
      self.water = water

    def baby(self):
    # make an object of the child class

 class Cow(Animal):
      pass

 new_cow = Cow("id" + str(randint(100000, 999999)), 100, 10)
 new_cow.baby() # make a new cow object

I don't even know how to start with the baby() method, but I hope you guys understand my question

Upvotes: 1

Views: 52

Answers (1)

deceze
deceze

Reputation: 522081

def baby(self):
    return type(self)()

type(self) gets you the class object of the current instance, e.g. Cow, and () makes a new instance of it, e.g. same as Cow(). Of course, Cow() requires three arguments, so either you have to provide them when you call baby, or otherwise pass them. E.g.:

def baby(self, *args):
    return type(self)(*args)

...
new_cow.baby(42, 100, 10)

Or:

def baby(self):
    return type(self)(self.identity + '1', self.food, self.water)

Upvotes: 2

Related Questions