educative.io

Is private property defined outside initializer a Class variable?

In the proposed solution, the properties seem to be created as Class Variables (i.e. outside the initializer).
In my understanding, those variables are expected to be shared between all Student Class’s instances.
Right?

But the following code works as expected (each Student’s instance has it own __name property properly set)

student1 = Student()
student1.setName("Alex")
student2 = Student()
student2.setName("John")
print("Student1 name: ", student1.getName())
print("Student2 name: ", student2.getName())

Output:

Student1 name: Alex
Student2 name: John

Did I misunderstand something?
Why the Class Variables are not shared by instances in this cases?

Hello @digital_monk,
I am a little confused about your question but let me try to answer it to the best of my abilities. So, the variables are first created and set to None. After which, the class functions are made to alter the value of the variable or to get the value of the variable. These variables are not supposed to be shared between two instances, as those two instances are created separately.

Hope this helps

Hello @Omer_Ahmed.

Thank you for your reply.

Hi @Omer_Ahmed, I think the original question is asking about the class variables __name and __rollNumber declared in Student:

class Student:
__name = None
__rollNumber = None

but these two class variables are not the ones being set in the setters, since in setName for example, we’re referencing self.__name and not __name, so we’re setting completely different instance variables.

def setName(self, name):
self.__name = name

The class variables are never used. I think having these two class variables in the solution is confusing to people. Let me know if I’m missing anything here


Course: https://www.educative.io/courses/learn-oop-in-python
Lesson: https://www.educative.io/courses/learn-oop-in-python/YM6mmqwQEXA