简体   繁体   中英

TypeError: 'str' object is not callable // class?

Here is my Transaction 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

And when I'm trying to run the date function:

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

I'm getting the following error:

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

How can I fix that?

In self.date = date , the self.date here actually hides the method def date(self) , so you should consider changing either the attribute or the method name.

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.

Fix:

    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()     

Output:

2013-10-25 00:00:00

You have an instance variable ( self.date ) and a method def date(self): by the same name. Upon constructing the instance, the former overwrites the later.

Consider renaming your method ( def get_date(self): ) or using properties .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM