2

I find this example very confusing since they are using two different arguments Why ?

class Person:
  def __init__(mysillyobject, name, age):
    mysillyobject.name = name
    mysillyobject.age = age

  def myfunc(abc):
    print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

2 Answers 2

5

The first parameter of an instance method is always a reference to the instance.

As a convention, you usually name this parameter self, however you are free to give the parameter any other valid name, as shown in the code you posted.

Sign up to request clarification or add additional context in comments.

Comments

1

So in python, for instance methods, the first argument is for the instance of the class. As mentioned in other answers, this is the self argument. But this is only by convention. You can go with anything from bananas to mysillyobject.

Thus, in your class, the myfunc() method is defined to take only one argument, which is the instance I mentioned earlier.

Hence, when you call myfunc() from p1 (where p1 is the object of the class Person), you are implicitly passing p1 for the argument abc mentioned in the definition :

def myfunc(abc): # p1 is passed for abc
    print("Hello my name is " + abc.name)

Thus, p1.name is accessed and printed to give a proper output

Comments

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.