Consider the following Python code where we add a custom attribute to an instance of a class. What will be printed?
class Car: def __init__(self, brand): self.brand = brand my_car = Car('Toyota') my_car.color = 'red' print(my_car.color)
Think about what happens when you add a new attribute directly to an instance.
The attribute color is added directly to the instance my_car. So printing my_car.color outputs 'red'.
Look at this code where a custom attribute is added to the class, not the instance. What will be the output?
class Dog: def __init__(self, name): self.name = name Dog.legs = 4 buddy = Dog('Buddy') print(buddy.legs)
Remember that instances can access class attributes if they don't have their own.
The attribute legs is added to the class Dog. The instance buddy can access it, so printing buddy.legs outputs 4.
What error will this code produce when trying to print a missing attribute?
class Book: def __init__(self, title): self.title = title novel = Book('1984') print(novel.author)
Think about what happens when you try to access an attribute that was never set.
Since author was never set on the instance or class, Python raises an AttributeError.
You want to add a new attribute category to all existing and future instances of a class Product. Which approach works?
Think about class attributes and how instances access them.
Adding category as a class attribute after instances exist makes it accessible to all instances unless overridden.
Given this code, what will be printed?
class Employee: department = 'Sales' emp1 = Employee() emp2 = Employee() emp1.department = 'Marketing' print(emp2.department)
Remember the difference between instance and class attributes.
Changing emp1.department creates an instance attribute for emp1 only. emp2.department still refers to the class attribute 'Sales'.