python - Use _replace method of namedtuple to update the fields of other data structures containing the nt -
i learning namedtuple. find way, using ._replace method, update appearances of namedtuple wherever are.
say have list of nodes, , lists of elements (two-node beams, four-node quads) , boundaries ("one node" elements) defined these nodes.
i playing around doing this:
from collections import namedtuple nt node = nt('node', 'x y') beam = nt('beam', 'i j') quad = nt('quad', 'i j k l') boundary = nt('boundary', 'b') #define nodes: n1 = node(0,0) n2 = node(0,1) n3 = node(1,1) n4 = node(1,0) #and other things using nodes: q1 = quad(n1,n2,n3,n4) b1 = boundary(n1) be1 = beam(n1,n4) now, if replace n1 new node:
n1 = n1._replace(x=0.5,y=0.5) print(n1) # node(x=0.5,y=0.5) none of other items updated:
print(b1) # boundary(b=node(x=0, y=0)) i understand python naming , object model , why behind this: b1.b has been set object node(0,0), not name n1. when n1 changed, other namedtuples still contain same object before, while n1 gets new object.
what alter behavior when alter n1, changes "felt" in b1, be1, q1, etc. how can this?
all instances of namedtuple-produced classes immutable. ._replace() creates new instance, doesn't update 1 instance phone call on.
because instances immutable cannot want namedtuple. you'll have provide such functionality in subclass, breaking immutability. or provide own node custom class allows attributes mutated directly:
class node(object): __slots__ = ('x', 'y') def __init__(self, x, y): self.x = x self.y = y def __repr__(self): homecoming '{0.__class__.__name__}({0.x!r}, {0.y!r})'.format(self) like namedtuple, class uses __slots__ cutting on memory use. can set x , y attributes straight on instances, , other references instance see change:
>>> class node(object): ... __slots__ = ('x', 'y') ... def __init__(self, x, y): ... self.x = x ... self.y = y ... def __repr__(self): ... homecoming '{0.__class__.__name__}({0.x!r}, {0.y!r})'.format(self) ... >>> n1 = node(10, 20) >>> n2 = n1 >>> n2 node(10, 20) >>> n1.x = 42 >>> n1.y = 81 >>> n2 node(42, 81) python
No comments:
Post a Comment