Python - Class with class attribute and instance attribute

Introduction

Here's a more comprehensive example of this behavior that stores the same name in two places.

class MixedNames:                            # Define class 
    data = 'test'                            # Assign class attr 
    def __init__(self, value):               # Assign method name 
        self.data = value                    # Assign instance attr 
    def display(self): 
        print(self.data, MixedNames.data)    # Instance attr, class attr 

This class contains two defs, which bind class attributes to method functions.

It also contains an = assignment statement.

This assignment assigns the name data inside the class, it lives in the class's local scope and becomes an attribute of the class object.

Class attributes are inherited and shared by all instances of the class.

Demo

class MixedNames:                            # Define class 
    data = 'test'                            # Assign class attr 
    def __init__(self, value):               # Assign method name 
        self.data = value                    # Assign instance attr 
    def display(self): 
        print(self.data, MixedNames.data)    # Instance attr, class attr 
# w  ww.  ja va 2  s . c o  m
x = MixedNames(1)          # Make two instance objects 
y = MixedNames(2)          # Each has its own data 
x.display(); y.display()   # self.data differs, MixedNames.data is the same

Result

data lives in two places:

  • in the instance objects created by the self.data assignment in __init__, and
  • in the class from which they inherit names created by the data assignment in the class.
  • The class's display method prints both versions, by first qualifying the self instance, and then the class.

Related Topic