问题描述
我希望能够通过在已实例化的对象上调用方法来创建对象的新实例。例如,我有一个对象:
I want to be able to create a new instance of an object by calling a method on an already instantiated object. For example, I have the object:
organism = Organism()
我希望能够调用 organism.reproduce()
并具有两个Organism类型的对象。此时我的方法如下:
I want to be able to call organism.reproduce()
and have two objects of type Organism. My method at this point looks like this:
class Organism(object):
def reproduce():
organism = Organism()
我很确定它不起作用(I'我甚至还不确定如何测试它。我在)。那么,如何使我的对象创建自己可访问的副本,就像我创建的第一个对象一样(使用 organism = Organism()
)?
and I'm pretty sure it doesn't work (I'm not really even sure how to test it. I tried the gc method in this post). So how can I make my object create a copy of itself that's accessible just like the first object I created (with organism = Organism()
)?
推荐答案
class Organism(object):
def reproduce(self):
#use self here to customize the new organism ...
return Organism()
另一种选择-如果在方法中未使用实例( self
):
Another option -- if the instance (self
) isn't used within the method:
class Organism(object):
@classmethod
def reproduce(cls):
return cls()
这可以确保生物产生更多的生物,(从生物衍生的假想的Borg产生更多的Borg)。
This makes sure that Organisms produce more Organisms and (hypothetical Borgs which are derived from Organisms produce more Borgs).
附带好处不需要使用 self
的原因在于,除了可以从实例调用之外,现在还可以直接从类中调用它:
A side benefit of not needing to use self
is that this can now be called from the class directly in addition to being able to be called from an instance:
new_organism0 = Organism.reproduce() # Creates a new organism
new_organism1 = new_organism0.reproduce() # Also creates a new organism
最后,如果实例( self
)和类( Organism 在方法中使用code>或子类(如果从子类调用):
Finally, if both the instance (self
) and the class (Organism
or subclasses if called from a subclass) are used within the method:
class Organism(object):
def reproduce(self):
#use self here to customize the new organism ...
return self.__class__() # same as cls = type(self); return cls()
在每种情况下,您d将其用作:
In each case, you'd use it as:
organism = Organism()
new_organism = organism.reproduce()
这篇关于从类方法创建新的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!