【问题标题】:How do you use an Iterator without that has no __iter__ method?如果没有 __iter__ 方法,如何使用迭代器?
【发布时间】:2021-04-09 11:02:54
【问题描述】:

在 Maya 中尝试一些基本编程时,我遇到了“MitMeshPolygon”方法。被描述为: “这个类是多边形表面(网格)的迭代器。”

(https://help.autodesk.com/view/MAYAUL/2016/ENU/?guid=__py_ref_class_open_maya_1_1_m_it_mesh_polygon_html)

这似乎是我需要的,所以我更多地研究了迭代器,据我所知,迭代器本身应该是可迭代的,并且有一个 iter 方法。但是,当尝试对其进行迭代时,python 告诉我它不可迭代。

        iterable = OpenMaya.MItMeshPolygon(dagPaths[0])            
        while not iterable.isDone():
            print(iterable)
            print(dir(iterable))

>

的代理

['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new ', '下一个', 'reduce', 'reduce_ex', 'repr', ' setattr', 'sizeof', 'str', 'subclasshook', 'swig_destroy' , 'weakref', 'center', 'className', 'count', 'currentItem', 'geomChanged', 'getArea', 'getAxisAtUV', 'getColor', 'getColorIndex', 'getColorIndices '、'getColors'、'getConnectedEdges'、'getConnectedFaces'、'getConnectedVertices'、'getEdges'、'getNormal'、'getNormals'、'g etPointAtUV','getPoints','getTriangle','getTriangles','getUV','getUVArea','getUVAtPoint','getUVIndex','getUVSetNames','getUVs','getVertices','hasColor','hasUVs' , 'hasValidTriangulation', 'index', 'isConnectedToEdge', 'isConnectedToFace', 'isConnectedToVertex', 'isConvex', 'isDone', 'isHoled', 'isLamina', 'isPlanar', 'isStarlike', 'isUVReversed', ' next','normalIndex','numColors','numConnectedEdges','numConnectedFaces','numTriangles','onBoundary','point','polygon','polygonVertexCount','reset','setIndex','setPoint' , 'setPoints', 'setUV', 'setUVs', 'tangentIndex', 'this', 'thisown', 'updateSurface', 'vertexIndex', 'zeroArea', 'zeroUVArea']

我想遍历所有多边形和“getArea”,但现在我不知道该怎么做,我读到的所有内容都告诉我迭代器应该是可迭代的,但程序告诉我不然。我在这里不明白什么?如何使用这些方法获取有关 DagPath 指示的对象的特定信息?

【问题讨论】:

  • for item in iterable: 不起作用吗?
  • 请注意,有一个__next__ 方法,因此您应该能够在while True: 循环内调用next(iterable),一旦完成,它将引发StopIteration
  • 不重复。这个对象不是 Python 中标准意义上的迭代器。您必须以某种特定于 Maya 的方式与之交互。查看方法列表,countnextcurrentItem 看起来可能是要走的路,但我对 Maya 的了解还不够,无法对应该如何使用这个东西有信心。跨度>
  • @user2357112supportsMonica 为什么在dir() 的输出中列出了__next__
  • @00: 奇怪...这不在在线文档中,并且缺少所有迭代器都应该拥有的__iter__。我猜这个东西可能有一半可以用作迭代器。

标签: python methods iterator maya-api


【解决方案1】:

您的iterable 有一个__next__ 方法。您也许可以执行以下操作:

iterator = OpenMaya.MItMeshPolygon(dagPaths[0])            
try:
    while True:
        item = next(iterator)
        ...
except StopIteration:
    pass

请注意,我已将变量重命名为 iterator,因为这似乎是更正确的术语。一个可迭代对象确实应该有一个__iter__ 方法,调用iter(iterable) 会将它变成一个执行实际迭代的迭代器,并且有一个__next__ 方法。

事实上,iterator 可能实际上是一个生成器,可以随时生成值(使用 next()),并且您将无法访问随机定位的值(例如,使用索引),只有一个在另一个之后。那么你只需要一个__next()__ 方法。但是没有看到MitMeshPolygon 的实际代码,这是一个猜测。

【讨论】:

    猜你喜欢
    • 2020-08-23
    • 2021-02-17
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2017-05-25
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多