lgwest
lgwest

Reputation: 1347

class members also creates instance members in python

It seems that python class members also are "secretly" copied to instance members, I have never heard of this. Is this described somewhere?

Here is a small example I did to investigate this (python 3.6.7 ubuntu 18:04).

class A:
    a = 'hello'  # class member

    def __init__(self):
        print(self.a)    # a has also become a instance member
        self.a = 'Hi'    # change the instance member of a
        print(A.a)       # class member a unchanged


a = A()

Upvotes: 1

Views: 39

Answers (1)

elemakil
elemakil

Reputation: 3811

This is not at all a "secret" copy. It is the intended behaviour and for example discussed here in the official reference (3.2. The standard type hierarchy: "Class instances"):

A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes. [...]

By creating an entry for the attribute in the class instance's dictionary, you shadow the class's attribute entry.

Let's walk through your example step-by-step:

    def __init__(self):
        print(self.a)    # (1.)
        self.a = 'Hi'    # (2.)
        print(A.a)       # (3.)
  1. Attribute lookup starts at the instance's attribute dict. No matching attribute is found, hence, lookup continues at the class's attribute dict. A matching attribute, a = 'hello', is found.
  2. An explicit assignment using the class instance creates a new attribute entry of name a in the class instance's attribute dict. Consequently, this attribute is unique to the class instance.
  3. The class attribute remains unchanged because it resides in an entirely different dict, the attribute dict of the class rather than the instance.

Upvotes: 1

Related Questions