Python Forum
[NEW CODER] TypeError: Object is not callable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[NEW CODER] TypeError: Object is not callable
#1
Hello all,

I just started my Python journey a couple of days ago. I typed the following code exactly as shown in the book I'm reading, but it returns an error message and I can't seem to figure out why.

Here's the code:
class Staff:
    def __init__ (self, pPosition, pName, pPay):
        self.position = pPosition
        self.name = pName
        self.pay = pPay
        print ("Creating Staff object")

    def __str__ (self):
        return "Position = %s, Name = %s, Pay = %d" %(self.position, self.name, self.pay)

    def calculatePay (self):
        prompt = "\nEnter number of hours worked for %s: " %(self.name)
        hours = input(prompt)
        prompt = "Enter the hourly rate for %s: " %(self.name)
        hourlyRate = input(prompt)
        self.pay = int(hours) * int(hourlyRate)
        return self.pay
I then create an object by typing the following:
 officeStaff1 = Staff ('Basic', 'Michael', 1) 
..to which I get the following message "Creating Staff Object"

When I type:
officeStaff1.name
I see Michael.

If I type:
officeStaff1.position
I see Basic

However, when I type:
officeStaff1.calculatePay()
The error message I am getting is:
Error:
Traceback (most recent call last): File "<pyshell#45>", line 1, in <module> officeStaff1.calculatePay() File "/Users/mikemusicmbp2/Desktop/classdemo.py", line 12, in calculatePay prompt = "\nEnter number of hours worked for %s: " %(self.name) TypeError: 'str' object is not callable
I've tried using comments to remove one line of code at a time in hopes that I'll see some type of clue. However, that hasn't worked. I have also tried Googling answers and that hasn't worked either. I don't have any programmer friends that I can ask so here I am. I have zero programming experience and have hit a wall.

Any help is very much appreciated. Thanks.

Attached Files

Thumbnail(s)
   
Reply
#2
I am not sure what is going on, the code you have shown doesn't look like it would give the error shown.
The error states that you are calling a str object, but I cant see that you are.

Edit: The codes runs for me with no errors

The following code is an example of what would trigger the error you are having.
"Example of code that would cause the error"()
Reply
#3
(Aug-20-2023, 11:34 AM)Yoriz Wrote: I am not sure what is going on, the code you have shown doesn't look like it would give the error shown.
The error states that you are calling a str object, but I cant see that you are.

Edit: The codes runs for me with no errors

The following code is an example of what would trigger the error you are having.
"Example of code that would cause the error"()

Thank you for your reply. It's so strange, now I'm getting a number of errors even though I haven't changed anything.

Attached Files

Thumbnail(s)
   
Reply
#4
(Aug-20-2023, 01:47 PM)iwantyoursec Wrote: Thank you for your reply. It's so strange, now I'm getting a number of errors even though I haven't changed anything.
Now is your code not connect with interactive shell you run.
So one way as show under is to use -i command.
So in same folder,as you see i can use cat command.
G:\div_code\egg
λ cat staff.py
class Staff:
    def __init__ (self, pPosition, pName, pPay):
        self.position = pPosition
        self.name = pName
        self.pay = pPay
        print ("Creating Staff object")

    def __str__ (self):
        return "Position = %s, Name = %s, Pay = %d" %(self.position, self.name, self.pay)

    def calculatePay (self):
        prompt = "\nEnter number of hours worked for %s: " %(self.name)
        hours = input(prompt)
        prompt = "Enter the hourly rate for %s: " %(self.name)
        hourlyRate = input(prompt)
        self.pay = int(hours) * int(hourlyRate)
        return self.pay

G:\div_code\egg
λ python -i staff.py
>>> officeStaff1 = Staff('Basic', 'Michael', 1)
Creating Staff object
>>> officeStaff1.name
'Michael'

>>> officeStaff1.calculatePay()
Enter number of hours worked for Michael: 10
Enter the hourly rate for Michael: 50
500
>>> exit()
To clean🧺 code up a bit.
class Staff:
    def __init__(self, position, name, pay):
        self.position = position
        self.name = name
        self.pay = pay
        print("Creating Staff object")

    def __str__(self):
        return f"Position = {self.position}, Name = {self.name}, Pay = {self.pay}"

    def calculate_pay(self):
        hours = input(f"Enter number of hours worked for {self.name}: ")
        hourly_rate = input(f"Enter the hourly rate for {self.name}: ")
        self.pay = int(hours) * int(hourly_rate)
        return self.pay
Reply
#5
Guys, I made a very silly mistake and I'm embarrassed about it. I forgot to run the Module first Doh . After running the Module, I then called it in the Shell and it worked as intended.

Thank you for your help.
Reply
#6
Your description of the error is confusing. Are you using IDLE?

IDLE is a bad tool. IDLE works differently than other Python IDE's or running Python from the shell. You can never be really sure if odd behaviors are due to an issue is in your code, or if it is another of IDLE's idiosyncrasies.

This is what happens when I run your code in Python. I copied your program to a file named test.py
Output:
(venv) C:\Users...\python_sandbox>python test.py (venv) C:\Users\...\python_sandbox>
Not much interesting there. The file defines a class but doesn't do anything. I add some statements to make it a bit more interesting. The extra staments only execute when this file is executed. They do not execute when this file is imported by another file.
class Staff:
    def __init__(self, pPosition, pName, pPay):
        self.position = pPosition
        self.name = pName
        self.pay = pPay
        print("Creating Staff object")

    def __str__(self):
        return "Position = %s, Name = %s, Pay = %d" % (
            self.position,
            self.name,
            self.pay,
        )

    def calculatePay(self):
        prompt = "\nEnter number of hours worked for %s: " % (self.name)
        hours = input(prompt)
        prompt = "Enter the hourly rate for %s: " % (self.name)
        hourlyRate = input(prompt)
        self.pay = int(hours) * int(hourlyRate)
        return self.pay


if __name__ == "__main__":
    # A little test program5
    officeStaff1 = Staff("Basic", "Michael", 1)
    print(officeStaff1.name)
    print(officeStaff1.position)
    print(officeStaff1.calculatePay())
Output:
(venv) C:\...\python_sandbox>python test.py Creating Staff object Michael Basic Enter number of hours worked for Michael: 5 Enter the hourly rate for Michael: 2 10 (venv) C:\...\python_sandbox>
Another way I can use his code is to start an interactive python interpreter, import the module, and type in python statements.
Output:
(venv) C:\...\python_sandbox>python Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep 5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from test import Staff >>> jeff = Staff("Manager", "Jeff", 5) Creating Staff object >>> jeff.name 'Jeff' >>> jeff.position 'Manager' >>> jeff.pay 5 >>> jeff.calculatePay() Enter number of hours worked for Jeff: 4 Enter the hourly rate for Jeff: 5 20 >>> quit()
Notice that Michael was not automatically created when I imported the file. This is because __name__ only equals "__main__" when executing a Python file. When importing a file, __name__ == filename of the imported module.

To make something that works like IDLE, I need to run the python program and use the "-i" option to tell Python to leave the interpreter open after executing the file. Since I am executing the file, I'll remove the test code at the bottom. I am tired of Michael.
Output:
(venv) C:\...\python_sandbox>python -i junk.py >>> jeff = Staff("Manager", "Jeff", 5) Creating Staff object >>> jeff.name 'Jeff' >>> jeff.position 'Manager' >>> jeff.pay 5 >>> jeff.calculatePay() Enter number of hours worked for Jeff: 4 Enter the hourly rate for Jeff: 5 20 >>> quit()
Some comments about your class:

Unless you are writing a class designed for input or output, it is unusual to have the class do input or output. Somebody using your class probably doesn't want it to print "Creating Staff object" each time they create an instance of your class. It is unlikely they will use the calculatePay() method because they probably have hours for the employee in a file or database and don't want to type in the values. I would write your class more like this:
class Staff:
    def __init__(self, position, name, rate):
        self.position = position
        self.name = name
        self.rate = rate

    def __str__(self):
        return f"{self.name}, {self.position}, Rate = {self.rate}"

    def pay(self, hours, rate=None):
        return hours * self.rate if rate is None else rate


if __name__ == "__main__":
    emp = Staff("CEO", "Guido", 42)
    print(f"{emp}. Pay for 10 hours = {emp.pay(10)}")
And now I can use that class in another program.
from staff import Staff  # Renamed generic class module "staff.py"

name, position, rate = input("Enter Employee Name, position, wage: ").split(",")
emp = Staff(position.strip(), name.strip(), float(rate))
hours = float(input(f"Enter hours for {emp.name}: "))
print(f"{emp} pay = {emp.pay(hours)}")
Output:
(venv) C...python_sandbox>python test_staff.py Enter Employee Name, position, wage: Guido, CEO, 42 Enter hours for Guido: 5 Guido, CEO, Rate = 42.0 pay = 210.0
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: cannot pickle ‘_asyncio.Future’ object Abdul_Rafey 1 413 Mar-07-2024, 03:40 PM
Last Post: deanhystad
  error in class: TypeError: 'str' object is not callable akbarza 2 525 Dec-30-2023, 04:35 PM
Last Post: deanhystad
Bug TypeError: 'NoneType' object is not subscriptable TheLummen 4 762 Nov-27-2023, 11:34 AM
Last Post: TheLummen
  TypeError: 'NoneType' object is not callable akbarza 4 1,021 Aug-24-2023, 05:14 PM
Last Post: snippsat
  Need help with 'str' object is not callable error. Fare 4 861 Jul-23-2023, 02:25 PM
Last Post: Fare
  TypeError: 'float' object is not callable #1 isdito2001 1 1,091 Jan-21-2023, 12:43 AM
Last Post: Yoriz
  TypeError: a bytes-like object is required ZeroX 13 4,190 Jan-07-2023, 07:02 PM
Last Post: deanhystad
  'SSHClient' object is not callable 3lnyn0 1 1,178 Dec-15-2022, 03:40 AM
Last Post: deanhystad
  TypeError: 'float' object is not callable TimofeyKolpakov 3 1,475 Dec-04-2022, 04:58 PM
Last Post: TimofeyKolpakov
  API Post issue "TypeError: 'str' object is not callable" makeeley 2 1,936 Oct-30-2022, 12:53 PM
Last Post: makeeley

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020