python创建类函数时为什么需要self

self是一个参数表示类本身。

class A(object):
    def __iter__(self):
        self.num=1
        return self
    def __next__():
        self.num=self.num+1
        return self.num-1
在next函数中如果你不加self函数就会报错告诉你没定义self.num因此你必须要在next中加入self对象。
class A(object):
    def __iter__(self):
        self.num=1
        return self
    def __next__(self):
        self.num=self.num+1
        return self.num-1
 
 
class A(object):
    def __iter__(self):
        self.num=1
        return self
    def __next__(self):
        self.num=self.num+1
        if self.num>10:
            raise StopIteration
        return self.num-1

for i in A():
    print(i)


iter是创建迭代对象,next是调用对象进行迭代。
posted @ 2023-02-27 11:51  祥瑞哈哈哈  阅读(201)  评论(0)    收藏  举报