[英]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.