Hi @Ricard I will try to help, because I had trouble with this concept to.
What helped was to understand that I have to look at the objects with the same eyes I look on functions.
You can have a function like this:
def foo():
example = 5
return example
And you call it like this:
foo()
It alway will return 5.
But you can have a function like this:
def bar(value):
example = value
return example
You will call it like this:
bar(6)
bar(2)
bar(4)
And it will allways return the value you passed to it as an argument. Example:
>>> 6
>>> 2
>>> 4
With classes it is similar.
You can have a class like this:
class MyStaticPet(object):
def __init__(self):
self.name = "MrSnuggles"
def print_pet_name(self):
print(self.name
You can define a instance of this class like this:
pet = MyStaticPet()
And call the function of this instance like this:
pet.print_pet_name()
The output will always be this:
>>> MrSnuggles
But you can have code like this:
class MyDynamicPet(object):
def __init__(self, name):
self.name = name
def print_pet_name(self):
print(self.name)
You can define a instance of this class like this:
pet_one = MyDynamicPet("Fluffy")
pet_two = MyDynamicPet("Goldy")
And call the function of this instance like this:
pet_one.print_pet_name()
pet_two.print_pet_name()
The output will be this:
>>> Fluffy
>>> Goldy
So, when you say self.name = name you say: take the input that is given to this parameter above in the parenthesis of the __init__
function and assign it to the variable self.name.
The __init__
function ist the constructor of a Python-Class and initializes the new instance with the values you pass to it through the parameter in the __init__(self, my_constructor_parameter)
. Everything you pass there will be the value or ‘character’ of the new instance. In the example above the value of the instance pet_one
is the string/name Fluffy
.
I have created for my self a mnemonic that helped me to understand the concept. I always say: Whats in it? And then will look at the parameter of __init__(self, i_am_in_it)
to see what the class takes.
Hope that helps a bit.
Kind regards,
Didier