calling a function from class in python - different way

后端 未结 5 1418
别那么骄傲
别那么骄傲 2021-02-04 09:54

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 a

5条回答
  •  滥情空心
    2021-02-04 10:42

    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

提交回复
热议问题