Appearance
Instance Attributes and Class Attributes
Since Python is a dynamic language, instances created from a class can bind attributes arbitrarily.
Binding Attributes to Instances
The method to bind attributes to an instance is through instance variables or the self
variable:
python
class Student(object):
def __init__(self, name):
self.name = name
s = Student('Bob')
s.score = 90
Binding Attributes to the Class
But what if the Student
class itself needs to bind an attribute? You can define the attribute directly within the class. This kind of attribute is a class attribute, owned by the Student
class:
python
class Student(object):
name = 'Student'
After defining a class attribute, although it belongs to the class, all instances of the class can access it. Let's test it:
python
>>> class Student(object):
... name = 'Student'
...
>>> s = Student() # Create instance s
>>> print(s.name) # Print the name attribute. Since the instance doesn't have a name attribute, it looks up the class's name attribute
Student
>>> print(Student.name) # Print the class's name attribute
Student
>>> s.name = 'Michael' # Bind a name attribute to the instance
>>> print(s.name) # Since the instance attribute has a higher priority than the class attribute, it overrides the class's name attribute
Michael
>>> print(Student.name) # However, the class attribute still exists and can be accessed using Student.name
Student
>>> del s.name # If you delete the instance's name attribute
>>> print(s.name) # Calling s.name again. Since the instance's name attribute is not found, the class's name attribute is displayed
Student
From the above example, it is clear that when writing programs, you should never use the same name for both instance attributes and class attributes. This is because an instance attribute with the same name will override the class attribute. However, if you delete the instance attribute and then use the same name, you will access the class attribute.
Exercise
To count the number of students, you can add a class attribute to the Student
class that automatically increments each time an instance is created:
python
class Student(object):
count = 0
def __init__(self, name):
self.name = name
Student.count += 1
# Test:
if Student.count != 0:
print('Test failed!')
else:
bart = Student('Bart')
if Student.count != 1:
print('Test failed!')
else:
lisa = Student('Lisa')
if Student.count != 2:
print('Test failed!')
else:
print('Students:', Student.count)
print('Test succeeded!')
Summary
Instance Attributes belong to each individual instance and do not interfere with each other.
Class Attributes belong to the class itself, and all instances share the same attribute.
Avoid using the same name for both instance attributes and class attributes to prevent hard-to-find errors.