加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – super的用法是什么(ClassName,self)._ init_()[复制

发布时间:2020-12-16 23:53:46 所属栏目:Python 来源:网络整理
导读:参见英文答案 Understanding Python super() with __init__() methods ????????????????????????????????????7个 我有一个看起来像这样的课程: #!/usr/bin/env pythonclass Foo: def __init__(self,x): self.x = x def bar(self): self.bar1_out = self.x +

参见英文答案 > Understanding Python super() with __init__() methods ????????????????????????????????????7个
我有一个看起来像这样的课程:

#!/usr/bin/env python
class Foo:
    def __init__(self,x):
        self.x = x
    def bar(self):
        self.bar1_out = self.x + 5
        self.bar2_out = self.x + 1
        return (self.bar1_out,self.bar2_out)
    def qux(self,myvalue = None):
        first,second = myvalue or self.bar()
        return first + 3,second + 6

def main():
    """docstring for main"""
    f = Foo(5)

    mbr_out1,mbr_out2 = f.bar()
    print mbr_out1,"t",mbr_out2

    mqx_out1,mqx_out2 = f.qux()
    print mqx_out1,mqx_out2

    qout1,qout2 = f.qux((1))
    print qout1,qout2

if __name__ == '__main__':
    main()

我看到一些建议使用super

    def __init__(self,x):
        super(Foo,self).__init__()
        self.x = x
    def bar(self)
        #etc.

我的问题是:

>什么是super(Foo,self)的使用.__ init __()
>它与self.x = x的区别
>如何通过使用super()使我的代码在上面生成相同的结果

最佳答案

How does it differ from self.x=x?

super()仅在您子类化时才有用:

class Foo(object):
    def __init__(self,x):
        self.x = x

class Bar(Foo):
    def __init__(self,x):
        super(Bar,self).__init__(x)
        self.initial_status = False

比在Bar的__init__中设置self.x = x更好.

不同之处在于Bar不需要关心Foo的实现.

如果你选择以设置self.x = 2 * x的方式更改Foo,那么你也不必更改Bar(它甚至可能位于差异文件中 – 几乎不能保证看到这一点).

在您的示例中,没有必要使用super(),因为您没有子类.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读