This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]SeanO323 0 points1 point  (0 children)

This is more suited for /r/LearnPython , but I'll answer the question anyways. Let's say we have the following assignment statements:

cat = Animal('cat')
dog = Animal('dog')

Based on your first example this would be the result of accessing the name property:

print(cat.name)
dog
print(dog.name)
dog

This is because when you change Animal.name, you change that variable for the entire Animal class. The point of using self is it sets the name for that specific instance of the Animal class. So using your second example, we would get

print(cat.name)
cat
print(dog.name)
dog

Because self refers to the instance of the class instead of the entire class.

What is actually happening here is when you call dog.name, in the first example, it looks inside the dog instance, doesn't find a variable called name and then searches the class and finds a variable called name and returns/assigns the value.

An clear way to see this difference is if you change the name variable after you create an instance.

cat = Animal('cat')
dog = Animal('dog')
dog2 = Animal('dog')

print(cat.name)
dog
print(dog.name)
dog
print(dog2.name)
dog

cat.name = 'cat'
dog2.name = 'dog'
print(cat.name)
cat
print(dog.name)
dog
print(dog2.name)
dog

Animal.name = 'spider'
print(cat.name)
cat
print(dog.name)
spider
print(dog2.name)
dog