Classes - functions - first parameter

Hi all !
How does abc.name, gets the name John , in the second function ?

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

So first of all it should be def __init__(mysillyobjecct, name, age).

Normally when we declare classes, the first variable that a function takes (like __init__ or myfunc in this example) is a variable, or pointer, to itself. Convention is that this variable is called self. In this example you use two different names for self. In the constructure you use mysillyobject and in myfunc you use abc. Because both these functions are part of the same class, they refer to the same object, ie self. you can use different names in the different functinos but they all refer to self. The first variable in any class method will be self, no matter what you call it.

In other words, mysillyobject.name , which is declared in the constructor and therefore available in the entire class, is exactly the same as abc.name. The code should really be written as follows:

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

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


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

Here you can see why it works. You just used different names for self in the different methods, but in this case it does not create different variables. They all refer to what we normally use as self.

Hope this helps!
Paul

1 Like

So the first function or method like Mosh says is the constructor, is this right ? and no matter how many functions(methods) are in the class, they all refer to the same class?

Yes. That’s correct. All methods that are indented under the class declaration is part of that class. The method with the name __init__ is the constructor.

1 Like

Finally something is clear, that’s a load of my mind. Thank you @Paul !!! :+1: :beer: