2016-05-28 34 views
3

在Python 3中,一切都应该是一个对象,偶数,但它们是不可变的是否可以为数字创建包装对象,例如浮动,使其可变吗?

是否可以为数字创建包装对象,例如:浮动,这样它会像普通数字一样运行,除非它必须是可变的吗?

我不知道是否会使用可行内置功能通过创建匿名包装对象从浮动派生,但改变它的行为是可变的。

>>> f = lambda x : type('', (float,), dict())(x) 
>>> a = f(9) 
>>> a 
9.0 

我必须改变˚F什么参数,使数一个是可变的?

我如何验证一个数是可变的:

我必须能够到f会从整数值创建一个浮点值和浅拷贝后,它会表现在以下方式创建这样的功能

>>> list_1 = [f(i) for i in [1, 2, 3, 4]] 
>>> list_1 
[1.0, 2.0, 3.0, 4.0] 
>>> list_2 = copy.copy(list_1) 
>>> list_1[0] *= 100 
>>> list_1 
[100.0, 2.0, 3.0, 4.0] 
>>> list_2 
[100.0, 2.0, 3.0, 4.0] 

修改第一个列表,改变了他们两个。

也许我必须添加一些字段到dict()或添加额外的基类强制可变性?

回答

3

值是不可变的。它们是柏拉图式的。像5 := 3这样的表达是无意义的。什么是可变的是locations,通常被称为地址或指针。 Python没有这些,但我们可以通过使用像list这样的容器类型来伪造它,这是一个真正的引用其他位置的位置。

下面是使用list来存储一个位置的局部实现,它使用list来存储一个位置,在该位置我们将保留该值的值,并在该值改变时更改该位置的值,并且由于可变数字的所有副本将分享该位置,所有副本会看到变化

import copy 

# Convenience to work with both normal and mutable numbers 
def _get_value(obj): 
    try: 
     return obj.value[0] 
    except: 
     return obj 

class mutable_number(object): 
    def __init__(self, value): 
     # Mutable storage because `list` defines a location 
     self.value = [value] 

    # Define the comparison interface 
    def __eq__(self, other): 
     return _get_value(self) == _get_value(other) 

    def __ne__(self, other): 
     return _get_value(self) != _get_value(other) 

    # Define the numerical operator interface, returning new instances 
    # of mutable_number 
    def __add__(self, other): 
     return mutable_number(self.value[0] + _get_value(other)) 

    def __mul__(self, other): 
     return mutable_number(self.value[0] * _get_value(other)) 

    # In-place operations alter the shared location 
    def __iadd__(self, other): 
     self.value[0] += _get_value(other) 
     return self 

    def __imul__(self, other): 
     self.value[0] *= _get_value(other) 
     return self 

    # Define the copy interface 
    def __copy__(self): 
     new = mutable_number(0) 
     new.value = self.value 
     return new 

    def __repr__(self): 
     return repr(self.value[0]) 

x = mutable_number(1) 
y = copy.copy(x) 
y *= 5 
print x 

list_1 = [mutable_number(i) for i in [1, 2, 3, 4]] 
list_2 = copy.copy(list_1) 
list_1[0] *= 100 
print list_1 
print list_2 

请让我知道,如果有不清楚的地方,我可以添加更多的文档

相关问题