在Python中合并/变形对象并保留旧引用

2024-05-15 04:34:46 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我在做一个招聘人员的面试任务。这项任务包括计算属于同一队的球员人数。我不必细说作业的细节,就能说明问题所在

  • 每个球员都有可能发展自己的团队
  • 这要求每个团队成员都有一个公共计数器的引用
  • 也有可能是两个队由于一个共同的球员而合并。在这种情况下,有两个团队和两个公共计数器
  • 现在合并后,希望两队的所有球员都参考同一个计数器

我知道一种方法是用其他球队的反参考更新一支球队的球员。但这听起来并不理想。因此,问题是

两个计数器如何合并两个公共计数器

在一般意义上,如何设计一个类,该类的对象可以以这样一种方式合并,即它们的结果对象可以被现有的引用引用

我甚至不知道如何描述我的需求:变形/合并对象?但我是用下面的代码做的。这是一个众所周知的设计模式(如转发)。在Python中有更好的方法吗

def morph(func):
    def wrapper(obj, *args):
        morpheus = obj
        _next = getattr(obj, 'morpheus', None)
        while _next:
            morpheus = _next
            _next = getattr(_next, 'morpheus', None)

        return func(morpheus, *args)

    return wrapper


class Counter(object):
    def __init__(self):
        self.count = 0

    @morph
    def incr(self, count=1):
        self.count += count

    @morph
    def morph_it(self, new_counter):
        if not isinstance(new_counter, Counter):
            raise TypeError("Can not morph into an object of different kind.")

        # Get effective object of this counter.
        new_counter = new_counter.get_counter()
        # Check it's not the same object.
        if self is not new_counter:
            new_counter.incr(self.count)
            setattr(self, 'morpheus', new_counter)

    @morph
    def get_count(self):
        return self.count

    @morph
    def get_counter(self):
        return self


class TestCounter(TestCase):
    def test_increment_after_morph(self):
        counter1 = Counter()
        counter2 = Counter()

        for i in range(10):
            counter1.incr()
        # Morph counter2 to counter1
        counter2.morph_it(counter1)
        self.assertEqual(counter1.get_count(), 10)
        self.assertEqual(counter2.get_count(), 10)

        counter1.incr()
        self.assertEqual(counter1.get_count(), 11)
        self.assertEqual(counter2.get_count(), 11)

        counter2.incr()
        self.assertEqual(counter1.get_count(), 12)
        self.assertEqual(counter2.get_count(), 12)

Tags: selfnewgetdefcountcounter计数器next

热门问题