2014-04-02 81 views
-1
class Duration(object): 
    def __init__(self, minutes, seconds): 
     self.minutes = minutes 
     self.seconds = seconds 

    def get_minutes(self): 
     return self.minutes 
    def get_seconds(self): 
     return self.seconds 
    def total_seconds(self): #This part is wrong 
     return 60*(self.get_minutes()) + self.get_seconds() 

这是我的代码。对象方向 - 返回值

我想找到总秒数(Duration(3, 30)).total_seconds)应该给我210但现在我得到这个<bound method Duration.total_seconds of <__main__.Duration object at 0x0211AD90>>
如何获得210

+1

** ** total_seconds是一种方法,你不打电话。您正在获得参考资料。 – tuxuday

+0

删除'get'方法,没有理由,因为你已经可以很好地访问'seconds'和'minutes'。 – kindall

回答

0

如果您希望能够跳过括号,使total_seconds一个property

@property 
def total_seconds(self): 

现在不正是你想要什么:

>>> Duration(3, 30).total_seconds 
210 
1

没有什么不对您,简单地说,你必须调用,而不是获取它的方法:

>>> print((Duration(3, 30)).total_seconds()) 
210 

total_seconds()total_seconds 当你调用它没有(),蟒蛇返回方法的实例但不会调用它。

+2

这是对的。所以原始代码是正确的,只是'print'调用它是错误的。 – rickcnagy

+0

好吧然后如果我想要(持续时间(3,30))。total_seconds)? – user3398505

+0

@ user3398505,这是它会给。你的电话不正确。我展示的是正确的。同样的结果。 – sshashank124

0

这应该是

print((Duration(3, 30)).total_seconds()) 
            ^^ 

在Python中,功能对象,并且可以被打印。这就是你所看到的。