合并/分组 class 个实例

Merging / grouping class instances

所以我有这个任务来练习抽象的多态性和用法类:

Create a class called Person. Upon initialization it will receive a name (str) and a surname (str). Create another class called Group. Upon initialization it should receive a name (str) and people (list of Person instances). Implement the needed magic methods, so the test code below works

和下面的测试代码:

p0 = Person('Aliko', 'Dangote')
p1 = Person('Bill', 'Gates')
p2 = Person('Warren', 'Buffet')
p3 = Person('Elon', 'Musk')
p4 = p2 + p3

first_group = Group('__VIP__', [p0, p1, p2])
second_group = Group('Special', [p3, p4])
third_group = first_group + second_group

print(len(first_group))
print(second_group)
print(third_group[0])

for person in third_group:
    print(person)

输出应该是:

3
Group Special with members Elon Musk, Warren Musk
Person 0: Aliko Dangote
Person 0: Aliko Dangote
Person 1: Bill Gates
Person 2: Warren Buffet
Person 3: Elon Musk
Person 4: Warren Musk

到目前为止我对魔术方法有基本的了解,用的比较少。 到目前为止我想出的代码如下:

from abc import ABC, abstractmethod

class Base(ABC):
    #TODO
"""
Magic method that will merge the name and surname of 2 Person class  instances or combine the lists (with Person class instances) of Group class instances
"""

    def __repr__(self):
        pass


class Person(Base):
    def __init__(self, name: str, surname: str):
        self.name = name
        self.surname = surname

    def __repr__(self):
        #TODO
        """Implement logic to get the idx of the Person class instance from the self.people list (some sort of duck
        typing?) that is called to be printed."""
        return f'Person {idx}: {self.name} {self.surname}'


class Group(Base):
    def __init__(self, name: str, people: list):
        self.name = name
        self.people = people

    def __repr__(self):
        people = [f'{p.name} {p.surname}' for p in self.people]
        return f'Group {self.name} with members {", ".join(people)}'

如有任何帮助,我们将不胜感激。提前致谢。

实现__len__,你可以使用len(first_group),__getitem__用于third_group[0], 这是代码:

class Person:
    idx = -1

    def __init__(self, name: str, surname: str):
        Person.idx += 1
        self.idx = Person.idx
        self.name = name
        self.surname = surname

    def __repr__(self):
        # TODO
        """Implement logic to get the idx of the Person class instance from the self.people list (some sort of duck
        typing?) that is called to be printed."""
        return f'Person {self.idx}: {self.name} {self.surname}'

    def __add__(self, other):
        if isinstance(other, Person):
            return Person(self.name, other.surname)
        else:
            raise TypeError(f'TypeError: unsupported operand type(s) for +: {type(self)} and {type(other)}')


class Group:
    def __init__(self, name: str, people: list):
        self.name = name
        self.people = people

    def __repr__(self):
        people = [f'{p.name} {p.surname}' for p in self.people]
        return f'Group {self.name} with members {",".join(people)}'

    def __add__(self, other):
        if isinstance(other, Group):
            return Group(self.name, self.people + other.people)
        else:
            raise TypeError(f'TypeError: unsupported operand type(s) for +: {type(self)} and {type(other)}')

    def __len__(self):
        return len(self.people)

    def __getitem__(self, item):
        if isinstance(item, int):
            return self.people[item]
        else:
            raise TypeError(f'need int but get {type(item)}')


p0 = Person('Aliko', 'Dangote')
p1 = Person('Bill', 'Gates')
p2 = Person('Warren', 'Buffet')
p3 = Person('Elon', 'Musk')
p4 = p2 + p3

first_group = Group('__VIP__', [p0, p1, p2])
second_group = Group('Special', [p3, p4])
third_group = first_group + second_group

print(len(first_group))
print(second_group)
print(third_group[0])

for person in third_group:
    print(person)