Ada*_*zek 3 python mutable immutability shallow-copy python-3.x
在 Python 3 中,一切都应该是一个对象,甚至是数字,但它们是不可变的。
是否可以为数字创建包装对象,例如 float,使其行为与普通数字完全相同,但它必须是可变的?
我想知道通过创建从 float 派生的匿名包装对象,但将其行为更改为可变的,使用内置类型函数是否可行。
>>> f = lambda x : type('', (float,), dict())(x)
>>> a = f(9)
>>> a
9.0
Run Code Online (Sandbox Code Playgroud)
我必须改变哪些参数˚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]
Run Code Online (Sandbox Code Playgroud)
修改了第一个列表,两个都改变了。
也许我必须向 dict() 添加一些字段或添加额外的基类来强制执行可变性?
值是不可变的。它们是柏拉图式的。像这样的表达5 := 3是荒谬的。什么是可变的locations,通常称为地址或指针。Python 没有这些,但我们可以通过使用像 alist这样的容器类型来伪造它,它实际上是一个引用其他位置的位置。
这是可变数字类型的部分实现,它使用 alist来存储一个位置,我们将在该位置保留数字的值并在该位置更改值时更改该位置的值,并且因为可变数字的所有副本将共享该位置,所有副本都会看到变化
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
Run Code Online (Sandbox Code Playgroud)
如果有任何不清楚的地方,请告诉我,我可以添加更多文档
| 归档时间: |
|
| 查看次数: |
698 次 |
| 最近记录: |