[英]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? 例如:
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
我什至不知道如何從 baby() 方法開始,但我希望你們能理解我的問題
def baby(self):
return type(self)()
type(self)
為您獲取當前實例的 class object,例如Cow
,並且()
創建它的新實例,例如與Cow()
相同。 當然, Cow()
需要三個 arguments,所以你要么在調用baby
時提供它們,要么通過它們。 例如:
def baby(self, *args):
return type(self)(*args)
...
new_cow.baby(42, 100, 10)
或者:
def baby(self):
return type(self)(self.identity + '1', self.food, self.water)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.