1

This is a class design question in python.

I am trying to design three classes, one for animal, one for zoo, one for chicken farm.

class Animal:
    pass

class Zoo:

    def __init__(self, listOfAnimals)

    .....

class chickenFarm(Zoo):
   ....

Note ChickenFarm is a child of Zoo and uses many of the zoo methods. Additionally, the chicken farm has its unique methods related only to chicken.

My question is, how the zoo class (or object) mutates into a chickenFarm object once all the animals in the zoo are found to be chicken? (Obviously the zoo class has methods that can add or remove animals)

in other words:

z=Zoo()

z.addAnimals()

z.removeanimals()

if z.testAllCkichen():

z now mutates into a chickenFarm objects

z.layEggs()

or maybe:

c=checkenFarm(z) # (when z now contains all chicken)

c.layEggs(0)
4

1 回答 1

0

这是您如何实现的开始,chickenFarm.__init__以便当它获取一个Zoo实例作为其第一个参数时,它将创建一个chickenFarm其属性从Zoo实例复制的:

class chickenFarm(Zoo):
    def __init__(self, *args, **kwargs):
        if args and isinstance(args[0], Zoo):
            zoo = args[0]
            # copy all Zoo data from zoo to self
            # for example self.animals = zoo.animals.copy()
        else:
            Zoo.__init__(self, *args, **kwargs)

然后你可以像这样使用它:

z = Zoo()
# do some stuff
if z.testAllChicken():
    c = chickenFarm(z)
    c.layEggs()
于 2013-04-12T00:03:57.803 回答