2013-11-03 31 views
0

我用下面的代码类实例化 - 多态性 - 的Python

class FooBar: 
    def __init__(self): 
     self.x = 0 
     self.y = 0 

    def __init__(self, x, y, z): 
     self.x = x 
     self.y = y 
     self.z = z 

我保存上述FooBar.py

当我使用,

import FooBar 
p = FooBar() 

错误说module object not callable。是什么原因?

+0

需要用'P = FooBar.FooBar()'或'使用从FooBar导入FooBar'。 – martineau

+0

你在哪里保存FooBar.py? –

回答

1

因为您导入的FooBar是模块,而不是类。

替换:

import FooBar 

有:

from FooBar import FooBar 

或者,如果你愿意的话,使用:

import FooBar 
# First FooBar is the module, second is the class within the module. 
p = FooBar.FooBar() 
+1

我不知道这个评论有多相关,但请记住,Python不是Java,您不必在包含类之后命名模块。模块是与相同目的相关的功能和类的逻辑分组。此外,模块应该以小写命名(以便您可以将它们与类别区分开来)。 –

1

第二def redeclare __init__方法。在python中,你不能重载方法。

+0

虽然你的答案通常是正确的,但这不是错误的根源。简单地说,第二个定义覆盖第一个定义。 –

+0

我认为,这是来自此用户的第二个答案的答案:) – histrio