super(ClassName,self)有什么用呢

2024-09-29 01:32:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一节课是这样的:

#!/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, "\t", mqx_out2

    qout1, qout2 = f.qux((1))
    print qout1, "\t", qout2

if __name__ == '__main__':
    main()

我看到了一些建议使用super的实现

^{pr2}$

我的问题是:

  1. super(Foo,self).__init__()有什么用
  2. 它与self.x=x有何不同
  3. 如何使用super()使上面的代码产生相同的结果

Tags: selffooinitmaindefbaroutprint
1条回答
网友
1楼 · 发布于 2024-09-29 01:32:34

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,那么您就不必同时更改{}(这甚至可能位于一个不同的文件中—几乎可以保证看不到这一点)。在

{t>你的例子中没有你的子类。在

相关问题 更多 >