Create new class instance from class method

后端 未结 6 2060
攒了一身酷
攒了一身酷 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:24

    What about something like this:

    class Organism(object):
    
        population = []
    
        def __init__(self, name):
            self.name = name
            self.population.append(self)
        def have_one_child(self, name):
            return Organism(name)
        def reproduce(self, names):
            return [self.have_one_child(name) for name in names]
    

    Result:

    >>> a = Organism('a')
    >>> len(Organism.population)
    1
    >>> a.reproduce(['x', 'y', 'z']) # when one organism reproduces, children are added
                                     # to the total population
                                     # organism produces as many children as you state
    [<__main__.Organism object at 0x05F23190>, <__main__.Organism object at 0x05F230F0>, <__main__.Organism object at 0x05F23230>]
    >>> for ele in Organism.population:
    ...     print ele.name
    ... 
    a
    x
    y
    z
    >>> Organism.population[3].reproduce(['f', 'g'])
    [<__main__.Organism object at 0x05F231D0>, <__main__.Organism object at 0x05F23290>]
    >>> for ele in Organism.population:
    ...     print ele.name
    ... 
    a
    x
    y
    z
    f
    g
    

提交回复
热议问题