2016-11-10 81 views
-2
class type_name: 
    def __init__(self, fields): 
     self._fields = fields 
     self._mutable = False 
     self.a = self._fields[0] 
     self.b = self._fields[1] 
     self.c = self._fields[2] 

    def _replace(self, **kargs): 
     if self._mutable: 
      for key, value in kargs.items(): 
       if key == 'a': 
        self.a = value 
       if key == 'b': 
        self.b = value 
       if key == 'c': 
        self.c = value 
      return None 
     else: 
      A = self.a, B = self.b, C = self.c 
      return self.type_name(**kargs) 

_replace方法需要** kargs作为输入。 _replace方法取决于存储在实例名称self._mutable中的值。 if self.mutable == True,它被调用的对象的实例名称被改变,并且方法返回None所以,如果origin = Point(0,0)并且我们调用origin._replace(y = 5),那么打印(原点)将显示为点(x = 0,y = 5),因为原点发生了变化。如何修复_replace方法

如果self.mutable == False,它将返回同一类的新对象,其实例名称的值相同,除了在kargs中指定的值。因此,如果origin = Point(0,0)并且我们调用new_origin = origin._replace(y = 5),则print(origin,new_origin)将显示为Point(x = 0,y = 0)Point(x = 0) ,y = 5),因为原点没有发生变异

我不确定我的函数_replace有什么问题,有人可以帮助我解决它吗?谢谢

+0

请正确使用''like'格式化文本正文' – martianwars

回答

1

__init__()不采取关键字参数,只有listfields。您可能需要改变你的__init__()方法或映射kwargslist

class type_name: 
    def __init__(self, fields): 
     self._fields = fields 
     self._mutable = False 
     self.a = self._fields[0] 
     self.b = self._fields[1] 
     self.c = self._fields[2] 

    def _replace(self, **kwargs): 
     if not self._mutable: 
      return type_name([kwargs[c] for c in 'abc']) 
     for key, value in kwargs.items(): 
      if key == 'a': 
       self.a = value 
      if key == 'b': 
       self.b = value 
      if key == 'c': 
       self.c = value 
     return None 

a = type_name([1,2,3]) 
b = a._replace(a=3, b=2, c=1) 
b.a 
# 3 

说实话,我不喜欢这种超负荷使用_replace()。创建2种不同的方法。

+0

我会重新考虑整个方法。应该有一个抽象基类,它具有可变或不可变的实现 - 从一开始就混合两种方法看起来就像是糟糕的设计。 –