Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating the values of variables inside a namedtuple() structure

Tags:

python

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.

like image 250
Sayan Maitra Avatar asked Mar 06 '17 05:03

Sayan Maitra


People also ask

How do I change a value in Namedtuple?

Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field. In this case, we have to use another private method _replace() to replace values of the field. The _replace() method will return a new named tuple.

What is the use of Namedtuple in Python?

Python's namedtuple() is a factory function available in collections . It allows you to create tuple subclasses with named fields. You can access the values in a given named tuple using the dot notation and the field names, like in obj. attr .

What does Namedtuple return in Python?

The namedtuple is a function that returns a new named tuple class. In other words, the namedtuple() is a class factory. The namedtuple function accepts the following arguments to generate a class: A class name that specifies the name of the named tuple class.

What is difference between Namedtuple and tuple?

Tuples are immutable, whether named or not. namedtuple only makes the access more convenient, by using names instead of indices. You can only use valid identifiers for namedtuple , it doesn't perform any hashing — it generates a new type instead.


1 Answers

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

like image 133
Wasi Ahmad Avatar answered Oct 02 '22 00:10

Wasi Ahmad