如何修复替换方法?

时间:2016-11-07 07:42:53

标签: python class

class type_name:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self._fields = [x,y]
        self._mutable = False 

     def _replace(self,**kargs ):
        for key, value in kargs.iteritems():
            z = zip(key,value)
        for x in z:
            for y in self.field:
                if x[0] == y:
                    self.x = x[1]
                if x[0] == y:
                    self.y = x[1]

_replace函数,它将** kargs作为参数(关键字args)。这允许名称kargs在方法中用作参数名称的dict及其匹配的参数值。 _replace方法的语义取决于实例名称self._mutable:

中存储的值

如果为True,则调用它的对象的实例名称,并且该方法返回None。因此,如果origin = Point(0,0)并且我们调用origin._replace(y = 5),则print(origin)将显示为Point(x = 0,y = 5),因为origin是变异的。

如果为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)因为原点没有变异

我不确定为什么我的替换功能不起作用,有人可以告诉我如何修复它吗?

我添加了bsc.txt以帮助理解:

c-->t1 = Triple1(1,2,3)
c-->t2 = Triple2(1,2,3)
c-->t3 = Triple3(1,2,3)
# Test replace (not mutable)
==-->t1._replace(a=2)-->Triple1(2,2,3)
==-->t1._replace(a=2,c=2)-->Triple1(2,2,2)
^-->t1._replace(a=2,c=2,d=2)-->TypeError
==-->t1-->Triple1(a=1,b=2,c=3)
# Test _replace (mutable)
c-->Triple1 = pnt('Triple1', 'a b c',mutable=True)
c-->t1 = Triple1(1,2,3)
e-->t1._replace(a=2,c=2)-->None
==-->t1-->Triple1(a=2,b=2,c=2)

1 个答案:

答案 0 :(得分:0)

这种任务有更清洁的api。请使用getattrsetattr。首先,您需要修复_fields param。它应该包含名称而不是值。

class type_name:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self._fields = ['x', 'y']
        self._mutable = False 

    def _replace(self, **kwargs):
        if self._mutable:
            for key, value in kwargs.iteritems():
                setattr(self, key, value)
        else:
            for field in self._fields:
                if field not in kwargs:
                    kwargs[field] = getattr(self, field)
            return self.__class__(**kwargs)