self parameter is different on functions why?

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)
- - Source


answered 1 week ago Mike Scotty #1

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.

answered 1 week ago Polaris000 #2

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 powered by Disqus