Junior — Middle
Can you explain what attributes are in classes in Python and how they are used?
sobes.tech AI
Answer from AI
In Python, class attributes are variables that belong to the class itself, rather than to individual instances. They are used to store data shared among all objects of the class.
Attributes can be:
- Instance attributes — unique to each object, usually defined inside the
__init__method. - Class attributes — shared among all instances, defined directly within the class body.
Example:
class Car:
wheels = 4 # class attribute
def __init__(self, color):
self.color = color # instance attribute
car1 = Car('red')
car2 = Car('blue')
print(car1.wheels) # 4
print(car2.wheels) # 4
print(car1.color) # red
print(car2.color) # blue
Class attributes are useful for storing constants or values common to all objects, while instance attributes are for data unique to each object.