0

Case1:

def ABS(ogh):                     
    print "XYZ is good"    

ABS('jk')

Works fine.

Case2:

class A(object):                           
      def ABS(ogh):                     
          print "XYZ is good"    

a=A()                                      
a.ABS('jk')

TypeError: ABS() takes exactly 1 argument 2 given)

Case3:-

class A(object):                           
      def ABS(ogh):                     
          print "XYZ is good"    

a=A()                                      
a.ABS()

This one works fine.

My doubt is why do I get error in Case2 and why there is no requirement of a variable while calling the function/method(here, since under class) ABS defined inside the class A?

3
  • 2
    Methods need a self argument. Commented Jan 11, 2019 at 19:01
  • I think you need a refresh on how to define classes and use methods in Python. Commented Jan 11, 2019 at 19:04
  • All class methods have the "self" parameter passed invisibly. You need to add it to the list of params or you'll get this "too many args" error. Commented Jan 11, 2019 at 19:06

1 Answer 1

1

When you define methods inside of a class, python implicitly passes a reference to the class as the first parameter. By custom this is called self. So in your Case 2 example, you get a TypeError saying you've given two arguments because python has passed a reference to your class A object which you've bound to the variable ogh, and then your explicitly passed argument 'jk' is unexpected.

Using this knowledge we can update your case to to the following which produces the expected result.

class A(object):                           
      def ABS(self, ogh):                     
          print "XYZ is good"    

a=A()                                      
a.ABS('jk')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was helpful ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.