2017-05-10 24 views
0

我上課是這樣的:如何檢查一個對象的字段在Python中是否發生了變化?

p1 = Point(5, 10) 

我想知道,如果這個類的任何字段改爲:

class Point(object): 
    def __init__(self, x, y): 
     self.x = x 
     self.y = y 

我通過創建這個類的一個實例。我猜想可能會有某種散列函數可以與我比較。

例如,在bash中,我可以編寫md5sum <<<"string", md5sum <<<"string"以分別獲得x,y。然後,我可以比較xy以確定它們是否與衆不同。

是否有一種類似的方法可用於Python的對象?

回答

2

您可以簡單地通過覆蓋__setattr__類方法來實現該目的。

In[6]: class Point(object): 
      def __init__(self, x, y): 
       self.x = x 
       self.y = y 
       self._changed = False 

      def __setattr__(self, key, value): 
       if key != '_changed': 
        self._changed = True 
       super(Point, self).__setattr__(key, value) 

      def is_changed(self): 
       return self._changed 

In[7]: p = Point(2,3) 
In[8]: p.is_changed() 
Out[8]: False 
In[9]: p.x = 23 
In[10]: p.is_changed() 
Out[10]: True 
0

是的,有一種方法來散列所有實例變量以檢測更改:

>>> p1 = Point(5, 10) 
>>> h = hash(frozenset(vars(p1).items()))  # Record a hash checksum 
>>> h == hash(frozenset(vars(p1).items()))  # Check for changes 
True 
>>> p1.x += 1         # Change the object data 
>>> h == hash(frozenset(vars(p1).items()))  # Check for changes 
False 

該技術使用:

相關問題