python - Is it possible to make wrapper object for numbers, e.g. float, to make it mutable? -
in python 3 supposed object, numbers, they're immutable.
is possible create wrapper object numbers, e.g. float, such behave ordinary numbers except must mutable?
i've wondered whether feasible using built-in type function creating anonymous wrapper object deriving float, changing behaviour mutable.
>>> f = lambda x : type('', (float,), dict())(x) >>> = f(9) >>> 9.0
what parameters must change f make number a mutable?
how verify if number mutable:
i must able create such function f create integer value float value , after shallow copy behave in following manner:
>>> list_1 = [f(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]
modification of first list, have changed both of them.
maybe must add fields dict() or add additional base class enforce mutability?
values immutable. they're platonic forms. expression 5 := 3
nonsensical. mutable locations
, referred addresses or pointers. python doesn't have those, can fake using container type list
, location references other locations.
here's partial implementation of mutable numerical type using list
store location keep value of number , change value in location when should change, , because copies of mutable number share location, copies see change
import copy # convenience work both normal , 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 location self.value = [value] # define 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 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 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 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) in [1, 2, 3, 4]] list_2 = copy.copy(list_1) list_1[0] *= 100 print list_1 print list_2
please let me know if unclear, , can add more documentation
Comments
Post a Comment