Python Forum
Getting error when called through instance method - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Getting error when called through instance method (/thread-16504.html)



Getting error when called through instance method - aankrose - Mar-02-2019

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'



RE: Getting error when called through instance method - ichabod801 - Mar-02-2019

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



RE: Getting error when called through instance method - aankrose - Mar-02-2019

Bunny Rabbit

Thanks for the clarification.