2016-02-13 30 views
2

這是可能的嗎?Python 2.7 - 如何將一個Class屬性(指針?)指定給一個變量(需要創建Oz-esque數據流變量)

這個想法是,我想有一個特殊的變量,在分配或獲取其值時做一些處理。我也希望它看起來像一個常規變量,所以點符號在這裏是一個問題。

我知道這不是很明確,但這正是我需要試圖複製Oz-esque Dataflow Variables

如果像這些類型的數據流變量已經在python庫中實現,請告訴我。

例子:

class Promise(object): 

    def __init__(self): 
     self._value = 'defalt_value' 

    @property 
    def value(self): 
     #some processing/logic here 
     return self._value 

    @value.setter 
    def value(self, value): 
     #some processing/logic here 
     self._value = value 

my_promise_obj = Promise() 
my_promise = my_promise_obj.value 

my_promise = 'Please, set my_promise_obj.value to this string' 

print ('Object`s Value:     ' + my_promise_obj.value) 
print ('My Variable`s value:    ' + my_promise) 
print ('Has I changed the class attr?: ' + str(my_promise == my_promise_obj)) 

回答

0

這句法不能在Python工作,爲此目的:

my_promise = 'Please, set my_promise_obj.value to this string' 

的原因是,它重新分配全球/本地名稱指向上述串;你不能掛鉤那個任務;在分配前甚至沒有諮詢my_promise指出的對象。

但是有很多選擇;最明顯的是像

  • 對象語法與set方法:

    my_promise.set('Please, set my_promise_obj.value to this string') 
    
  • 的方法,封閉件,或任何與__call__方法對象:

    my_promise('Please, set my_promise_obj.value to this string') 
    
  • 與對象數據描述符:

    my_promise.value = 'Please, set my_promise_obj.value to this string' 
    

什麼的完全發瘋似的(只是可能性羣衆的一些例子):

  • __iadd__對象:

    my_promise += 'Please, set my_promise_obj.value to this string' 
    
  • __xor__對象:

    my_promise^'Please, set my_promise_obj.value to this string' 
    
  • __rrshift__的對象:

    'Please, set my_promise_obj.value to this string' >> my_promise 
    

可重寫到設定的值。

1

你需要重寫

def __setattr__(self, k, v): 

def __getattr__(self, k): 
1

如果我理解你的問題正確的話,你要控制的變量會發生什麼點符號分配和訪問?像你可以在C++中使用operator=

在Python中,變量總是包含對值的引用。據我所知,你不能攔截這個。

但是,你可以定義一個類Var和重載一些其他運營商,例如<<~,並有這樣的代碼:

v = Var() 
w = ~v # wait for v to get a value and assign it to w 
v << 42 # single-assignment of a value to v 

但我不知道這將是比value特性更好如你的例子。

相關問題