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.
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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With