Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的可重用对象_Python - Fatal编程技术网

Python中的可重用对象

Python中的可重用对象,python,Python,有些类的实例在Python中是可移植的,但只有dunder “iter()”方法,而不是“下一步()” 您的\uu iter\uu方法正在使用下一个函数返回一个对象: z = Vector2d(4, 5) z_iter = z.__iter__() print(type(z_iter)) for coord in z: print(coord) # <type 'generator'> 这确实提供了本机迭代功能——同样是以一种非常愚蠢的方式 编辑:在较旧的pytho

有些类的实例在Python中是可移植的,但只有dunder “iter()”方法,而不是“下一步()”


您的
\uu iter\uu
方法正在使用
下一个
函数返回一个对象:

z = Vector2d(4, 5)

z_iter = z.__iter__()

print(type(z_iter))

for coord in z:
    print(coord)

# <type 'generator'>
这确实提供了本机迭代功能——同样是以一种非常愚蠢的方式


编辑:在较旧的python 2.x版本中,将
next()
替换为
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。我忘了具体是哪个了。

你的问题是什么?通过
\uuuuuu iter\uuuu
返回的生成器对象确实有一个
\uuuu next\uuuu
方法。是的。因为所有的iterables都有一个
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法,但只有迭代器有一个
\uuuuu。因此,遵循最佳实践,您将拥有
ContainerClass
ContainerIterator
,这是许多样板文件,这是生成器的一大优点,它们让我们可以方便地生成迭代器,而不需要单独的类!我在报告中详细阐述了这一点
z = Vector2d(4, 5)

z_iter = z.__iter__()

print(type(z_iter))

for coord in z:
    print(coord)

# <type 'generator'>
class Vector2d:
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)
        self.index = 0

    def __iter__(self):
        return self

    def next(self):
        if self.index < 2:
            ret = [self.x, self.y][self.index]
            self.index += 1
            return ret
        else:
            raise StopIteration()


v = Vector2d(1, 2)
for coord in v:
    print(coord)