ohb*_*sme 33 python copy object
我希望能够通过调用已实例化的对象上的方法来创建对象的新实例.例如,我有对象:
organism = Organism()
我希望能够调用organism.reproduce()并拥有两个类型为Organism的对象.我的方法在这一点看起来像这样:
class Organism(object):
def reproduce():
organism = Organism()
Run Code Online (Sandbox Code Playgroud)
并且我很确定它不起作用(我甚至不确定如何测试它.我在这篇文章中尝试了gc方法).那么我怎样才能让我的对象创建一个可以访问的副本,就像我创建的第一个对象一样organism = Organism()?
mgi*_*son 50
class Organism(object):
def reproduce(self):
#use self here to customize the new organism ...
return Organism()
Run Code Online (Sandbox Code Playgroud)
另一个选项 - 如果self在方法中没有使用instance():
class Organism(object):
@classmethod
def reproduce(cls):
return cls()
Run Code Online (Sandbox Code Playgroud)
这可以确保生物体产生更多的生物体(假设的生物体来源于生物体产生更多的生物体).
不需要使用的另一个好处self是,除了能够从实例调用之外,现在可以直接从类中调用它:
new_organism0 = Organism.reproduce() # Creates a new organism
new_organism1 = new_organism0.reproduce() # Also creates a new organism
Run Code Online (Sandbox Code Playgroud)
最后,如果在方法中使用了instance(self)和类(Organism或者从子类调用的子类):
class Organism(object):
def reproduce(self):
#use self here to customize the new organism ...
return self.__class__() # same as cls = type(self); return cls()
Run Code Online (Sandbox Code Playgroud)
在每种情况下,您都将它用作:
organism = Organism()
new_organism = organism.reproduce()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33106 次 |
| 最近记录: |