Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

python - Create new class instance from class method

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()

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()

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())?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
class Organism(object):
    def reproduce(self):
        #use self here to customize the new organism ...
        return Organism()

Another option -- if the instance (self) isn't used within the method:

class Organism(object):
    @classmethod
    def reproduce(cls):
        return cls()

This makes sure that Organisms produce more Organisms and (hypothetical Borgs which are derived from Organisms produce more Borgs).

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

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()

In each case, you'd use it as:

organism = Organism()
new_organism = organism.reproduce()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...