Skip to main content
 首页 » 编程设计

Python 2.7之如何将类属性(指针)分配给变量(需要它来创建 Oz-esque 数据流变量)

2024年10月24日9lovecherry

有可能吗?

我的想法是我想要一个特殊的变量,它在分配或获取其值时进行一些处理。我还希望它看起来像一个常规变量,所以点符号在这里是个问题。

我知道这不是很明确,但这是我尝试复制 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)) 

请您参考如下方法:

此语法无法在 Python 中用于该目的:

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

原因是它重新分配了全局/本地名称以指向所述字符串;你不能 Hook 那个任务;并且在赋值之前它甚至不咨询 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 
    

可以重写以设置值。