[python] Calling a class method raises a TypeError in Python

I don't understand how classes are used. The following code gives me an error when I try to use the class.

class MyStuff:
    def average(a, b, c): # Get the average of three numbers
        result = a + b + c
        result = result / 3
        return result

# Now use the function `average` from the `MyStuff` class
print(MyStuff.average(9, 18, 27))

Error:

File "class.py", line 7, in <module>
    print(MyStuff.average(9, 18, 27))
TypeError: unbound method average() must be called with MyStuff instance as first argument (got int instance instead)

What's wrong?

This question is related to python python-3.x class methods

The answer is


In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.


To minimally modify your example, you could amend the code to:

class myclass(object):
        def __init__(self): # this method creates the class object.
                pass

        def average(self,a,b,c): #get the average of three numbers
                result=a+b+c
                result=result/3
                return result


mystuff=myclass()  # by default the __init__ method is then called.      
print mystuff.average(a,b,c)

Or to expand it more fully, allowing you to add other methods.

class myclass(object):
        def __init__(self,a,b,c):
                self.a=a
                self.b=b
                self.c=c
        def average(self): #get the average of three numbers
                result=self.a+self.b+self.c
                result=result/3
                return result

a=9
b=18
c=27
mystuff=myclass(a, b, c)        
print mystuff.average()

Every function inside a class, and every class variable must take the self argument as pointed.

class mystuff:
    def average(a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result
    def sum(self,a,b):
            return a+b


print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok

If class variables are involved:

 class mystuff:
    def setVariables(self,a,b):
            self.x = a
            self.y = b
            return a+b
    def mult(self):
            return x * y  # This line will raise an error
    def sum(self):
            return self.x + self.y

 print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
 print mystuff.mult() # should raise error
 print mystuff.sum()  # should be ok

Try this:

class mystuff:
    def average(_,a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result

#now use the function average from the mystuff class
print mystuff.average(9,18,27)

or this:

class mystuff:
    def average(self,a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result

#now use the function average from the mystuff class
print mystuff.average(9,18,27)

From your example, it seems to me you want to use a static method.

class mystuff:
  @staticmethod
  def average(a,b,c): #get the average of three numbers
    result=a+b+c
    result=result/3
    return result

print mystuff.average(9,18,27)

Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.


You need to spend a little more time on some fundamentals of object-oriented programming.

This sounds harsh, but it's important.

  • Your class definition is incorrect -- although the syntax happens to be acceptable. The definition is simply wrong.

  • Your use of the class to create an object is entirely missing.

  • Your use of a class to do a calculation is inappropriate. This kind of thing can be done, but it requires the advanced concept of a @staticmehod.

Since your example code is wrong in so many ways, you can't get a tidy "fix this" answer. There are too many things to fix.

You'll need to look at better examples of class definitions. It's not clear what source material you're using to learn from, but whatever book you're reading is either wrong or incomplete.

Please discard whatever book or source you're using and find a better book. Seriously. They've mislead you on how a class definition looks and how it's used.

You might want to look at http://homepage.mac.com/s_lott/books/nonprog/htmlchunks/pt11.html for a better introduction to classes, objects and Python.


Every function inside a class, and every class variable must take the self argument as pointed.

class mystuff:
    def average(a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result
    def sum(self,a,b):
            return a+b


print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok

If class variables are involved:

 class mystuff:
    def setVariables(self,a,b):
            self.x = a
            self.y = b
            return a+b
    def mult(self):
            return x * y  # This line will raise an error
    def sum(self):
            return self.x + self.y

 print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
 print mystuff.mult() # should raise error
 print mystuff.sum()  # should be ok

In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.


You need to spend a little more time on some fundamentals of object-oriented programming.

This sounds harsh, but it's important.

  • Your class definition is incorrect -- although the syntax happens to be acceptable. The definition is simply wrong.

  • Your use of the class to create an object is entirely missing.

  • Your use of a class to do a calculation is inappropriate. This kind of thing can be done, but it requires the advanced concept of a @staticmehod.

Since your example code is wrong in so many ways, you can't get a tidy "fix this" answer. There are too many things to fix.

You'll need to look at better examples of class definitions. It's not clear what source material you're using to learn from, but whatever book you're reading is either wrong or incomplete.

Please discard whatever book or source you're using and find a better book. Seriously. They've mislead you on how a class definition looks and how it's used.

You might want to look at http://homepage.mac.com/s_lott/books/nonprog/htmlchunks/pt11.html for a better introduction to classes, objects and Python.


You never created an instance.

You've defined average as an instance method, thus, in order to use average you need to create an instance first.


In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.


Every function inside a class, and every class variable must take the self argument as pointed.

class mystuff:
    def average(a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result
    def sum(self,a,b):
            return a+b


print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok

If class variables are involved:

 class mystuff:
    def setVariables(self,a,b):
            self.x = a
            self.y = b
            return a+b
    def mult(self):
            return x * y  # This line will raise an error
    def sum(self):
            return self.x + self.y

 print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
 print mystuff.mult() # should raise error
 print mystuff.sum()  # should be ok

From your example, it seems to me you want to use a static method.

class mystuff:
  @staticmethod
  def average(a,b,c): #get the average of three numbers
    result=a+b+c
    result=result/3
    return result

print mystuff.average(9,18,27)

Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.


Every function inside a class, and every class variable must take the self argument as pointed.

class mystuff:
    def average(a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result
    def sum(self,a,b):
            return a+b


print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok

If class variables are involved:

 class mystuff:
    def setVariables(self,a,b):
            self.x = a
            self.y = b
            return a+b
    def mult(self):
            return x * y  # This line will raise an error
    def sum(self):
            return self.x + self.y

 print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
 print mystuff.mult() # should raise error
 print mystuff.sum()  # should be ok

You never created an instance.

You've defined average as an instance method, thus, in order to use average you need to create an instance first.


From your example, it seems to me you want to use a static method.

class mystuff:
  @staticmethod
  def average(a,b,c): #get the average of three numbers
    result=a+b+c
    result=result/3
    return result

print mystuff.average(9,18,27)

Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.


In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.


You never created an instance.

You've defined average as an instance method, thus, in order to use average you need to create an instance first.


You need to spend a little more time on some fundamentals of object-oriented programming.

This sounds harsh, but it's important.

  • Your class definition is incorrect -- although the syntax happens to be acceptable. The definition is simply wrong.

  • Your use of the class to create an object is entirely missing.

  • Your use of a class to do a calculation is inappropriate. This kind of thing can be done, but it requires the advanced concept of a @staticmehod.

Since your example code is wrong in so many ways, you can't get a tidy "fix this" answer. There are too many things to fix.

You'll need to look at better examples of class definitions. It's not clear what source material you're using to learn from, but whatever book you're reading is either wrong or incomplete.

Please discard whatever book or source you're using and find a better book. Seriously. They've mislead you on how a class definition looks and how it's used.

You might want to look at http://homepage.mac.com/s_lott/books/nonprog/htmlchunks/pt11.html for a better introduction to classes, objects and Python.


Try this:

class mystuff:
    def average(_,a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result

#now use the function average from the mystuff class
print mystuff.average(9,18,27)

or this:

class mystuff:
    def average(self,a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result

#now use the function average from the mystuff class
print mystuff.average(9,18,27)

From your example, it seems to me you want to use a static method.

class mystuff:
  @staticmethod
  def average(a,b,c): #get the average of three numbers
    result=a+b+c
    result=result/3
    return result

print mystuff.average(9,18,27)

Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items