Python 2.7 - 用于左值修改的干净语法

时间:2017-08-21 01:29:29

标签: python python-2.7 struct mutable lvalue

具有类似结构的类型是很常见的,预计不会被远程的副本持有者修改。

字符串是一个基本的例子,但这是一个简单的例子,因为它是可以理解的不可变的 - 即使允许对文字字符串进行方法调用等事情,Python也是不常见的。

问题在于(在大多数语言中)我们经常会遇到类似(x,y) Point类的问题。我们偶尔会想要独立更改xy。即,从使用角度来看,Point LVALUE应该是可变的(即使副本不会看到变异)。

但是Python 2.7似乎没有提供任何选项来启用自动分配复制。所以这意味着我们实际上必须使我们的Point类IMMUTABLE,因为无意中的引用将在整个地方被创建(通常是因为有人忘记在将对象传递给其他人之前克隆该对象)。

不,我对无数的黑客不感兴趣,这些黑客只允许对象进行变异"当它被创建时#34;因为这是一个弱的概念而不是规模。

这些情况的逻辑结论是我们需要我们的变异方法来实际修改LVALUE。例如%=支持这一点。问题是,使用更合理的语法会更好,例如使用__setattr__和/或定义set_xset_y方法,如下所示。

class Point(object):
# Python doesn't have copy-on-assignment, so we must use an immutable
# object to avoid unintended changes by distant copyholders.

    def __init__(self, x, y, others=None):
        object.__setattr__(self, 'x', x)
        object.__setattr__(self, 'y', y)

    def __setattr__(self, name, value):
        self %= (name, value)
        return self # SHOULD modify lvalue (didn't work)

    def __repr__(self):
        return "(%d %d)" % (self.x, self.y)

    def copy(self, x=None, y=None):
        if x == None: x = self.x
        if y == None: y = self.y
        return Point(x, y)

    def __eq__ (a,b): return a.x == b.x and a.y == b.y
    def __ne__ (a,b): return a.x != b.x or  a.y != b.y
    def __add__(a,b): return Point(a.x+b.x, a.y+b.y)
    def __sub__(a,b): return Point(a.x-b.x, a.y-b.y)

    def set_x(a,b): return a.copy(x=b) # SHOULD modify lvalue (didn't work)
    def set_y(a,b): return a.copy(y=b) # SHOULD modify lvalue (didn't work)

    # This works in Python 2.7. But the syntax is awful.
    def __imod__(a,b):
        if   b[0] == 'x': return a.copy(x=b[1])
        elif b[0] == 'y': return a.copy(y=b[1])
        else:             raise AttributeError,  \
                "Point has no member '%s'" % b[0]



my_very_long_and_complicated_lvalue_expression = [Point(10,10)] * 4


# modify element 0 via "+="   -- OK
my_very_long_and_complicated_lvalue_expression[0] += Point(1,-1)

# modify element 1 via normal "__set_attr__"   -- NOT OK
my_very_long_and_complicated_lvalue_expression[1].x = 9999

# modify element 2 via normal "set_x"  -- NOT OK
my_very_long_and_complicated_lvalue_expression[2].set_x(99)

# modify element 3 via goofy "set_x"   -- OK
my_very_long_and_complicated_lvalue_expression[3]    %='x',   999


print my_very_long_and_complicated_lvalue_expression

结果是:

[(11 9), (10 10), (10 10), (999 10)]

正如您所看到的,+=%=工作正常,但其他任何事情似乎都无法奏效。当然语言发明者已经为LVALUE修改创建了一个基本语法,不仅限于看起来很傻的运算符。我似乎无法找到它。请帮忙。

2 个答案:

答案 0 :(得分:1)

在Python中,典型的模式是在修改之前复制而不是在赋值时复制。你可以用你想要的语义实现某种数据存储,但它看起来很多工作。

答案 1 :(得分:0)

我觉得我们已经在寻找预先存在的解决方案,尽职尽责。鉴于“< =”是某些语言的分配(例如,Verilog),我们可以非常直观地介绍:

value_struct_instance<<='field', value

作为Pythonic形式的

value_struct_instance.field = value

以下是一个用于指导目的的更新示例:

# Python doesn't support copy-on-assignment, so we must use an
# immutable object to avoid unintended changes by distant copyholders.
# As a consequence, the lvalue must be changed on a field update.
#
# Currently the only known syntax for updating a field on such an
# object is:
#
#      value_struct_instance<<='field', value
# 
# https://stackoverflow.com/questions/45788271/

class Point(object):

    def __init__(self, x, y, others=None):
        object.__setattr__(self, 'x', x)
        object.__setattr__(self, 'y', y)

    def __setattr__(self, name, value):
        raise AttributeError, \
            "Use \"point<<='%s', ...\" instead of \"point.%s = ...\"" \
            % (name, name)

    def __repr__(self):
        return "(%d %d)" % (self.x, self.y)

    def copy(self, x=None, y=None):
        if x == None: x = self.x
        if y == None: y = self.y
        return Point(x, y)

    def __ilshift__(a,b):
        if   b[0] == 'x': return a.copy(x=b[1])
        elif b[0] == 'y': return a.copy(y=b[1])
        else:             raise AttributeError,  \
                "Point has no member '%s'" % b[0]

    def __eq__ (a,b): return a.x == b.x and a.y == b.y
    def __ne__ (a,b): return a.x != b.x or  a.y != b.y
    def __add__(a,b): return Point(a.x+b.x, a.y+b.y)
    def __sub__(a,b): return Point(a.x-b.x, a.y-b.y)



my_very_long_and_complicated_lvalue_expression = [Point(10,10)] * 3

# modify element 0 via "+="
my_very_long_and_complicated_lvalue_expression[0] += Point(1,-1)

# modify element 1 via "<<='field'," (NEW IDIOM)
my_very_long_and_complicated_lvalue_expression[1]<<='x', 15
print my_very_long_and_complicated_lvalue_expression
# result:
# [(11 9), (15 10), (10 10)]

my_very_long_and_complicated_lvalue_expression[1]<<='y', 25
print my_very_long_and_complicated_lvalue_expression
# result:
# [(11 9), (15 25), (10 10)]

# Attempt to modify element 2 via ".field="
my_very_long_and_complicated_lvalue_expression[2].y = 25
# result:
# AttributeError: Use "point<<='y', ..." instead of "point.y = ..."