TypeError:'str'对象不可调用// class?

时间:2013-10-20 16:16:09

标签: python class

这是我的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

我该如何解决?

2 个答案:

答案 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 :(得分:1)

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

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