Python中的聚合(OOP概念)是否限制子对象被其他对象拥有?

Sid*_*gga 0 python oop class aggregation python-3.x

我读到这样一句话:“当对象有自己的生命周期并且子对象只能与一个父对象关联时,就会发生聚合”。但是,它对我的​​代码运行良好:-

class Country:
    def __init__(self, name=None, population=0):
        self.name = name
        self.population = population

    def printDetails(self):
        print("Country Name:", self.name)
        print("Country Population", self.population)


class Person:
    def __init__(self, name, country):
        self.name = name
        self.country = country

    def printDetails(self):
        print("Person Name:", self.name)
        self.country.printDetails()

class Man:
    def __init__(self, name, country):
        self.name = name
        self.country = country

    def printDetails(self):
        print("Person Name:", self.name)
        self.country.printDetails()



c = Country("Wales", 1500)
p = Person("Joe", c)
m = Man('John', c);
p.printDetails()
m.printDetails()

c.printDetails()
Run Code Online (Sandbox Code Playgroud)

Joh*_*ger 5

我读到这样一句话:“当对象有自己的生命周期并且子对象只能与一个父对象关联时,就会发生聚合”。然而,它对于我的代码来说工作得很好[...]

你误会了。您引用的陈述是“聚合”定义的一部分。您当然可以编写以不同方式执行操作的代码,但由于它这样做,它并没有演示聚合 - 至少不是根据您正在查看的定义。