calling a function from class in python - different way

后端 未结 5 1420
别那么骄傲
别那么骄傲 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 11:00

    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)
    

提交回复
热议问题