最近我在做一个招聘人员的面试任务。这项任务包括计算属于同一队的球员人数。我不必细说作业的细节,就能说明问题所在
我知道一种方法是用其他球队的反参考更新一支球队的球员。但这听起来并不理想。因此,问题是
两个计数器如何合并两个公共计数器
在一般意义上,如何设计一个类,该类的对象可以以这样一种方式合并,即它们的结果对象可以被现有的引用引用
我甚至不知道如何描述我的需求:变形/合并对象?但我是用下面的代码做的。这是一个众所周知的设计模式(如转发)。在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)
目前没有回答
相关问题 更多 >
编程相关推荐