25

I want to create a structure, as we do in C, in python. I have tried to use namedtuple() for this. However, I can not update the values of variables I have described inside the custom structure. Here is how i declared it:

from collections import namedtuple as nt
Struct = nt('Struct','all left right bottom top near far')

And this is what i am trying to do in a method :

class codeClip:
    def compOutCode(x,y,z,xmin,xmax,ymin,ymax,zmin,zmax):
        code = Struct(0,0,0,0,0,0,0)  
        if(y > ymax):
            code.top = 1
            code.all += code.top
        elif(y < ymin):
            code.bottom = 1            
        return code

However it is giving this error:

code.top = 1 AttributeError: can't set attribute

What should I do? Pardon me, I am fairly new in python, so still getting used to all of these.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
Sayan Maitra
  • 251
  • 1
  • 3
  • 4
  • 2
    Possible duplicate of [Changing values of a list of namedtuples](http://stackoverflow.com/questions/31252939/changing-values-of-a-list-of-namedtuples) – AKS Mar 06 '17 at 05:43

1 Answers1

34

You may use the _replace() method.

Instead of code.top = 1, you can update values as follows.

code = code._replace(top = 1)

Please note, named tuples are immutable, so you cannot manipulate them. If you want something mutable, you can use recordtype.

Reference: https://stackoverflow.com/a/31253184/5352399

Community
  • 1
  • 1
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • If you are referencing to a SO post which answers the question, then why not mark/flag this question as duplicate by referencing to the same post? – AKS Mar 06 '17 at 05:42
  • @AKS good point, i didn't notice the reference post first. later i edited my answer to tag that reference post because I think that post is useful. but before that i already posted answer and didn't remove it. also note, there are several questions in SO which are related to named tuple but not all questions are similar to this one. so, it took sometime to find the one that i am referencing. – Wasi Ahmad Mar 06 '17 at 05:45
  • @downvoter downvoted because i didn't flag the post as duplicate? – Wasi Ahmad Mar 06 '17 at 06:02
  • Instead of "recordtype" you could use SimpleNamespace which is in the standard library. – bcb May 31 '21 at 00:52