Could you clarify some ideas behind Python classes and class instances?
Consider this:
class A():
name = 'A'
a = A()
a.name = 'B' # point 1 (instance of class A is used here)
print a.name
print A.name
prints:
B
A
if instead in point 1 I use class name, output is different:
A.name = 'B' # point 1 (updated, class A itself is used here)
prints:
B
B
Even if classes in Python were some kind of prototype for class instances, I’d expect already created instances to remain intact, i.e. output like this:
A
B
Can you explain what is actually going on?
First of all, the right way in Python to create fields of an instance (rather than class fields) is using the
__init__method. I trust that you know that already.Python does not limit you in assigning values to non-declared fields of an object. For example, consider the following code:
So what’s going in your code is:
Awith a static fieldnameassigned withA.A,a.a(but not for other instances ofA) and assignBto ita.name, which is unique to the objecta.A.name, which belongs to the class