[python] calling a function from class in python - different way

EDIT2: Thank you all for your help! EDIT: on adding @staticmethod, it works. However I am still wondering why i am getting a type error here.

I have just started OOPS and am completely new to it. I have a very basic question regarding the different ways I can call a function from a class. I have a testClass.py file with the code:

class MathsOperations:
    def __init__ (self, x, y):
        self.a = x
        self.b = y
    def testAddition (self):
        return (self.a + self.b)

    def testMultiplication (self):
        return (self.a * self.b)

I am calling this class from another file called main.py with the following code:

from testClass import MathsOperations

xyz = MathsOperations(2, 3)
print xyz.testAddition()

This works without any issues. However, I wanted to use the class in a much simpler way.

I have now put the following code in the testClass.py file. I have dropped the init function this time.

class MathsOperations:
    def testAddition (x, y):
        return x + y

    def testMultiplication (a, b):
        return a * b

calling this using;

from testClass import MathsOperations
xyz = MathsOperations()
print xyz.testAddition(2, 3)

this doesn't works. Can someone explain what is happening wrongly in case 2? How do I use this class?

The error i get is "TypeError: testAddition() takes exactly 2 arguments (3 given)"

This question is related to python oop class methods

The answer is


you have to use self as the first parameters of a method

in the second case you should use

class MathOperations:
    def testAddition (self,x, y):
        return x + y

    def testMultiplication (self,a, b):
        return a * b

and in your code you could do the following

tmp = MathOperations
print tmp.testAddition(2,3)

if you use the class without instantiating a variable first

print MathOperation.testAddtion(2,3)

it gives you an error "TypeError: unbound method"

if you want to do that you will need the @staticmethod decorator

For example:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

then in your code you could use

print MathsOperations.testAddition(2,3)

class MathsOperations:
    def __init__ (self, x, y):
        self.a = x
        self.b = y
    def testAddition (self):
        return (self.a + self.b)

    def testMultiplication (self):
        return (self.a * self.b)

then

temp = MathsOperations()
print(temp.testAddition())

Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

You need to have an instance of a class to use its methods. Or if you don't need to access any of classes' variables (not static parameters) then you can define the method as static and it can be used even if the class isn't instantiated. Just add @staticmethod decorator to your methods.

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y
    @staticmethod
    def testMultiplication (a, b):
        return a * b

docs: http://docs.python.org/library/functions.html#staticmethod


disclaimer: this is not a just to the point answer, it's more like a piece of advice, even if the answer can be found on the references

IMHO: object oriented programming in Python sucks quite a lot.

The method dispatching is not very straightforward, you need to know about bound/unbound instance/class (and static!) methods; you can have multiple inheritance and need to deal with legacy and new style classes (yours was old style) and know how the MRO works, properties...

In brief: too complex, with lots of things happening under the hood. Let me even say, it is unpythonic, as there are many different ways to achieve the same things.

My advice: use OOP only when it's really useful. Usually this means writing classes that implement well known protocols and integrate seamlessly with the rest of the system. Do not create lots of classes just for the sake of writing object oriented code.

Take a good read to this pages:

you'll find them quite useful.

If you really want to learn OOP, I'd suggest starting with a more conventional language, like Java. It's not half as fun as Python, but it's more predictable.


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 oop

How to implement a simple scenario the OO way When to use 'raise NotImplementedError'? PHP: cannot declare class because the name is already in use Python class input argument Call an overridden method from super class in typescript Typescript: How to extend two classes? What's the difference between abstraction and encapsulation? An object reference is required to access a non-static member Java Multiple Inheritance Why not inherit from List<T>?

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