Python Forum

Full Version: Getting error when called through instance method
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Python Experts

Below code works without any issues when i called it though class method BUT when i called it through instance method , it is not working , may i please know why?

Working Code

class Pizza:
    def __init__(self, size):
        self.size = size
    def get_size(self):
        return "Size={}".format(self.size)

print(Pizza.get_size(Pizza(4555))
Output:
==> Size=4555
Error Code
class Pizza:
    def __init__(self, size):
        self.size = size
    def get_size(self, data):
        return "Size={}".format(self.size)

print(Pizza.get_size(4555))
Error:
aankrose@PS1:~/code$ python3 phase2.py Traceback (most recent call last): File "phase2.py", line 7, in <module> print(Pizza.get_size(4555)) TypeError: get_size() missing 1 required positional argument: 'data'
It's not class method vs. instance method. The get_size method is an instance method in both cases. And you don't call it from any instances. So it's an unbound instance method, which you have to explicitly provide an instance to. That's what you do in the first example (Pizza(4555) is the instance you are providing). In the second example you only provide an integer, and it is expecting an instance and an integer.

What you want to do is call it from an instance, so it is a bound method, and the instance parameter is provided implicitly.

class Pizza:
    def __init__(self, size):
        self.size = size
    def get_size(self):
        return "Size={}".format(self.size)

za = Pizza(4555)
print(za.get_size())
Bunny Rabbit

Thanks for the clarification.