Create new class instance from class method

后端 未结 6 2063
攒了一身酷
攒了一身酷 2020-12-23 19:39

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 = Organ

6条回答
  •  无人及你
    2020-12-23 20:30

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

提交回复
热议问题