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.
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
data lives in two places: