Class attributes and instance attributes
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
An attribute can be attached not only to an object but to the class itself. Then it is shared by all objects:
class Robot:
planet = "Earth" # a class attribute — one for everybody
count = 0
def __init__(self, name):
self.name = name # an instance attribute — each has its own
Robot.count += 1 # change the shared counter
a = Robot("R2-D2")
b = Robot("C-3PO")
Robot.count # 2
a.planet # 'Earth' — an object sees the class attributes
How Python looks up an attribute: first in the object, then in the class. Hence a trap: self.count += 1 would create a new attribute on the object, and the shared counter would stay at zero. That's why shared data is changed through the class name: Robot.count.
Another trap is mutable values in class attributes:
class Team:
members = [] # ONE list for all teams!
If each object needs its own list, create it in __init__: self.members = [].
Task. Create a class Robot that has a class attribute count (how many robots have been created) and an instance attribute name.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.