我有一节课是这样的:
#!/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
的实现
我的问题是:
super(Foo,self).__init__()
有什么用self.x=x
有何不同super()
使上面的代码产生相同的结果
super()
仅在您的子类中有用:比在
Bar
的__init__
中设置self.x = x
要好。在区别在于
Bar
不需要关心Foo
的实现。在如果您选择以设置}(这甚至可能位于一个不同的文件中—几乎可以保证看不到这一点)。在
self.x = 2 * x
的方式更改Foo
,那么您就不必同时更改{{t>你的例子中没有你的子类。在
相关问题 更多 >
编程相关推荐