[GIS] Handling QgsVectorLayer

pyqgis

I am trying to start with PyQGIS and make a simple script in the processing toolbox.

##theVector=vector
theVec = processing.getObject(theVector)
features = theVec.getFeatures()

now, if I'd like to iterate over every Object I'd write:

for feature in features:

but I just want to get the first object, and NOT interate over everyone..
I have tried:

f1 = features.get(1)

and get

'QgsFeatureIterator' object has no attribute 'get' See log for more details

How do I get just one feature?

Best Answer

It is a pure Python problem not limited to PyQGIS. I learn Python before using PyQGIS and the Help of PyQGIS.

In pure Python examine the attributes of feature with the dir() function:

dir(features)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'close', 'isClosed', 'next', 'nextFeature', 'rewind']

And there is no get here, hence the error: QgsFeatureIterator' object has no attribute 'get' See log for more details when you try f1 = features.get(1).

In contrats, features has the __iter__ method which means that you can use a for loop, look at Understanding Python Iterables and Iterators

When Python executes the for loop, it first invokes the iter() method of the container to get the iterator of the container. It then repeatedly calls the next() method (next() method in Python 3.x) of the iterator until the iterator raises a StopIteration exception. Once the exception is raised, the for loop ends. (when Python executes the for loop, it first invokes the iter() method of the container to get the iterator of the container)

So for feature in features is the same as features.next(), features.next(),...

Therefore the answer of Underdark features.next() is a pure Python problem, not limited to the Help of PyQGIS (The same kind of problem existed with Avenue, even with the Help)

Related Question