python中 return self的作用

举个例子

class A:
    def __init__(self):
        self.c=0
    def count(self):
        self.c+=1
        print(self.c)
a=A()
a.count()
#1

当我们想对实例对象的方法进行连续调用

a.count().count()
AttributeError: 'NoneType' object has no attribute 'count'

self其实就是实例对象本身,那么return self 就是返回实例对象本身
这时候对实例方法进行多次调用就成功了。

class A:
    def __init__(self):
        self.c = 0

    def count(self):
        self.c += 1
        print(self.c)
        return self
a = A()
a.count().count().count()
#1
#2
#3
发布了24 篇原创文章 · 获赞 8 · 访问量 2167

猜你喜欢

转载自blog.csdn.net/weixin_44839513/article/details/103653211