2013-10-20 65 views
-1

这里是我Transaction类:TypeError:'str'对象不可调用// class?

class Transaction(object): 
    def __init__(self, company, price, date): 
     self.company = company 
     self.price = price 
     self.date = date 
    def company(self): 
     return self.company 
    def price(self): 
     return self.price 
    def date(self): 
     self.date = datetime.strptime(self.date, "%y-%m-%d") 
     return self.date 

,当我试图运行date功能:

tr = Transaction('AAPL', 600, '2013-10-25') 
print tr.date() 

,我发现了以下错误:

Traceback (most recent call last): 
    File "/home/me/Documents/folder/file.py", line 597, in <module> 
    print tr.date() 
TypeError: 'str' object is not callable 

如何我能解决这个问题吗?

+0

你不能有一个与方法同名的实例变量,显然 –

回答

2

self.date = date中,self.date这里实际上隐藏了方法def date(self),所以您应该考虑更改属性或方法名称。

print Transaction.date # prints <unbound method Transaction.date> 
tr = Transaction('AAPL', 600, '2013-10-25') #call to __init__ hides the method 
print tr.date   # prints 2013-10-25, hence the error. 

修正:

def convert_date(self): #method name changed 
     self.date = datetime.strptime(self.date, "%Y-%m-%d") # It's 'Y' not 'y' 
     return self.date 

tr = Transaction('AAPL', 600, '2013-10-25') 
print tr.convert_date()  

输出:

2013-10-25 00:00:00 
+1

我正准备自己写这个,然后我看到你已经写过了:P –

1

您有一个实例变量(self.date)和由相同的名称的方法def date(self):。在构造实例时,前者覆盖后者。

考虑重命名您的方法(def get_date(self):)或使用properties