2016-11-07 24 views
0
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作爲參數名稱和它們的匹配參數值的詞典。 _replace方法的語義取決於存儲在實例名稱self._mutable中的值:如何解決替換方法?

如果爲True,則更改其調用的對象的實例名稱,並返回None。所以,如果origin = Point(0,0)並且我們調用origin._replace(y = 5),那麼print(origin)會顯示爲Point(x = 0,y = 5),因爲原點是變異的。

如果爲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) 
+0

我不能完全確定你想要做什麼,但它聽起來像你需要'如果self.is_mutable','setattr',並且使對象的副本.. – Sayse

+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)