2014-11-23 60 views
0
class Car: 
    # constructor 
    def __init__(self, make, model, year, mpg): 
     # instance variables 
     self.carMake = make 
     self.carModel=model 
     self.carYear = year 
     self.efficiency=mpg 
     self.gas = 0 

    # special method 
    def __str__(self): 
     return "%s %s %s"%(self.carYear, self.carMake, self.carModel) 

    def refuel(self,gallon): 
     if gallon < 0: 
      print("Sorry, amount cannot be negative") 
     else: 
      self.gas=self.gas+gallon 
      print (self.gas) 
      print("Added %.2f gallon of gas to the tank"%(self.gas)) 

    def gas(self): 
     print(self.gas) 


> Traceback (most recent call last): File "<pyshell#12>", line 1, in 
> <module> 
>  c1.gas() TypeError: 'int' object is not callable 

回答

0

对不起你self.gas__init__()方法初始化为int,但你定义了一个名为gas()以及方法。一旦__init__()运行,self.gasint。我猜你正在调用gas()这个类的实例。

重命名gas()方法类似print_gas(),或者,只要你打电话这一点,而不是做c1.gas(),只是做print c1.gas

0

考虑这类测试在一个名为test.py:

class Test: 
    def __init__(self): 
     self.x=3 
    def x(self): 
     print self.x 

现在我进口类测试在我的控制台,看看有什么方法有:

>>> from test import Test 
>>> [method for method in dir(Test) if callable(getattr(Test, method))] 
['__init__', 'x'] 

注意,它有方法x。现在让我们创建测试

的实例
>>> k=Test() 

让我们来看看什么样的方法,我们有

>>> [method for method in dir(k) if callable(getattr(k, method))] 
['__init__'] 
>>> 

正如你所看到的方法,x是不再可用。为什么?

当你创建k作为试验的一个实例,它执行__init__方法,并认为这self.x=3重新定义X是刚刚在self和可变你的方法x()已经一去不复返了。所以当你做k.x()它认为你在中设置的self.x这是不可调用的。然而刚刚k.x将作为我在下面:

>>> k.x() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'int' object is not callable 
>>> k.x 
3 
>>> 

得出的结论是没有命名变量和方法相同。

1

您的方法gas和您在__init__中创建的实例属性gas具有相同的名称。该方法存储在类中,但被存储在实例上的属性“隐藏”,因为Python首先在实例上查找名称,然后在类及其父项上查找名称。因此self.gas是一个整数,你不能调用它。

相关问题