1

I am trying to create new instance attributes (NOT feature attributes) for a collection of features in a vector layer in PyQGIS. I'm getting some weird results and am wondering if this is even possible. For instance, I can change the instance attributes of a single feature:

feat = iface.activeLayers().getFeatures().next()

feat.NEW = 'attribute'

And it seems to commit to that feature:

dir(feat)

['NEW', '__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__geo_interface__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'attribute', 'attributes', 'deleteAttribute', 'fieldNameIndex', 'fields', 'geometry', 'geometryAndOwnership', 'id', 'initAttributes', 'isValid', 'setAttribute', 'setAttributes', 'setFeatureId', 'setFields', 'setGeometry', 'setGeometryAndOwnership', 'setValid']

feat.NEW

'attribute'

However, when I try to iterate through the features using a feature iterator, I get no such luck!

for feat in iface.activeLayer().getFeatures():
    feat.NEW = 'attribute'

Then check:

feat = iface.activeLayer().getFeatures().next()

feat.NEW

Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'QgsFeature' object has no attribute 'NEW'

I'm assuming that the feature iterator creates some objects that have access to the features within the layer but does not actually point to the feature objects themselves... does anyone know of a way to iteratively change the instance attributes of PyQGIS objects? Is this even possible?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.