-1

这是我的Transaction课:

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

我该如何解决?

4

2 回答 2

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
于 2013-10-20T16:18:22.587 回答
1

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

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

于 2013-10-20T16:18:43.423 回答