Bird
Raised Fist0
Pythonprogramming~10 mins

Adding custom attributes in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Adding custom attributes
Create object
Add custom attribute
Access or modify attribute
Use attribute in code
End
This flow shows how to create an object, add a custom attribute to it, then access or modify that attribute during program execution.
Execution Sample
Python
class Car:
    pass

car = Car()
car.color = 'red'
print(car.color)
This code creates an empty class Car, adds a custom attribute 'color' to an instance, and prints its value.
Execution Table
StepActionObject StateOutput
1Define class Car (empty)Car class created, no attributes
2Create instance car = Car()car is an instance of Car, no attributes yet
3Add attribute car.color = 'red'car now has attribute 'color' with value 'red'
4Print car.colorcar.color is 'red'red
5End of programNo changes
💡 Program ends after printing the custom attribute value.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
carundefinedCar instance with no attributesCar instance with color='red'SameSame
car.colorundefinedundefined'red''red''red'
Key Moments - 2 Insights
Why can we add an attribute to an object that was not defined in the class?
In Python, objects can have attributes added dynamically after creation, as shown in step 3 of the execution_table where 'color' is added to 'car' even though Car class is empty.
What happens if we try to access an attribute that was never added?
Trying to access a non-existent attribute causes an AttributeError. Here, we only access 'car.color' after adding it in step 3, so no error occurs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what attribute does 'car' have?
A'color' with value 'red'
BNo attributes
C'color' with value 'blue'
D'speed' with value 100
💡 Hint
Check the 'Object State' column at step 3 in the execution_table.
At which step is the attribute 'color' first created on 'car'?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for when 'car.color' appears in the variable_tracker and execution_table.
If we tried to print 'car.speed' instead of 'car.color', what would happen?
AIt would print 'speed' value if set before
BIt would print 'null'
CIt would cause an error because 'speed' was never added
DIt would print an empty string
💡 Hint
Refer to key_moments about accessing attributes not added to the object.
Concept Snapshot
Adding custom attributes in Python:
- Create an object from a class
- Add attribute by assignment: obj.attr = value
- Access attribute by obj.attr
- Attributes can be added anytime after object creation
- Accessing missing attributes causes errors
Full Transcript
This example shows how to add custom attributes to Python objects. First, we define an empty class Car. Then, we create an instance called car. Next, we add a new attribute 'color' to car by assigning car.color = 'red'. Finally, we print car.color which outputs 'red'. Python allows adding attributes dynamically to objects after they are created. Trying to access an attribute that was never added will cause an error. This is a simple way to customize objects without changing the class definition.

Practice

(1/5)
1. What does adding a custom attribute to a Python object allow you to do?
easy
A. Delete the object from memory
B. Change the object's type permanently
C. Store extra information directly on that object
D. Prevent the object from being used in functions

Solution

  1. Step 1: Understand what attributes are

    Attributes are values or properties stored inside an object to hold data or state.
  2. Step 2: Adding custom attributes

    When you add a custom attribute, you attach new data directly to that object, allowing it to hold extra information.
  3. Final Answer:

    Store extra information directly on that object -> Option C
  4. Quick Check:

    Custom attributes = extra data on object [OK]
Hint: Custom attributes add new data fields to objects [OK]
Common Mistakes:
  • Thinking attributes change the object's type
  • Confusing attributes with deleting objects
  • Believing attributes restrict object usage
2. Which of the following is the correct syntax to add a custom attribute color with value 'red' to an object car?
easy
A. car.color = 'red'
B. car['color'] = 'red'
C. car->color = 'red'
D. car.color('red')

Solution

  1. Step 1: Identify attribute assignment syntax

    In Python, attributes are assigned using dot notation: object.attribute = value.
  2. Step 2: Check each option

    car.color = 'red' uses dot notation correctly. car['color'] = 'red' uses dictionary syntax which is invalid for normal objects. car->color = 'red' uses arrow notation which is not Python syntax. car.color('red') tries to call attribute as a method, which is incorrect here.
  3. Final Answer:

    car.color = 'red' -> Option A
  4. Quick Check:

    Use dot notation to add attributes [OK]
Hint: Use dot notation: object.attribute = value [OK]
Common Mistakes:
  • Using dictionary syntax on objects
  • Using arrow (->) like in other languages
  • Calling attribute as a function
3. What will be the output of this code?
class Dog:
    pass

my_dog = Dog()
my_dog.age = 5
print(my_dog.age)
medium
A. AttributeError
B. age
C. Dog
D. 5

Solution

  1. Step 1: Understand attribute assignment

    The code creates an empty class Dog and an instance my_dog. Then it adds a custom attribute age with value 5 to my_dog.
  2. Step 2: Print the attribute value

    Printing my_dog.age outputs the value stored, which is 5.
  3. Final Answer:

    5 -> Option D
  4. Quick Check:

    Custom attribute value prints correctly [OK]
Hint: Print attribute after assignment to see its value [OK]
Common Mistakes:
  • Expecting class name or attribute name as output
  • Thinking attribute does not exist yet
  • Confusing attribute with method call
4. Find the error in this code that tries to add a custom attribute height to an object person:
class Person:
    def __init__(self, name):
        self.name = name

person = Person('Alice')
person.height = 170
print(person['height'])
medium
A. Missing height parameter in __init__
B. Using person['height'] instead of person.height
C. Cannot add attributes after object creation
D. Name attribute should be height

Solution

  1. Step 1: Check how attribute is added

    The code correctly adds height using dot notation: person.height = 170.
  2. Step 2: Identify incorrect attribute access

    Printing uses person['height'], which is dictionary syntax and invalid for normal objects. It should be person.height.
  3. Final Answer:

    Using person['height'] instead of person.height -> Option B
  4. Quick Check:

    Access attributes with dot, not brackets [OK]
Hint: Use dot notation to access attributes, not brackets [OK]
Common Mistakes:
  • Using dictionary syntax on objects
  • Thinking attributes must be in __init__
  • Believing attributes can't be added later
5. You want to add a custom attribute status to multiple instances of a class Task only if their priority is above 5. Which code correctly does this?
hard
A. for t in tasks: if t.priority > 5: t.status = 'urgent'
B. for t in tasks: t.status = 'urgent' if t.priority > 5 else None
C. for t in tasks: if t.priority > 5: t['status'] = 'urgent'
D. for t in tasks: t.status = 'urgent' if t.priority <= 5: del t.status

Solution

  1. Step 1: Understand the condition and attribute addition

    We want to add status only if priority > 5, so we check this condition inside the loop.
  2. Step 2: Check each option's logic and syntax

    for t in tasks: if t.priority > 5: t.status = 'urgent' adds status only when priority > 5 using dot notation correctly. for t in tasks: t.status = 'urgent' if t.priority > 5 else None assigns status to None for others, which adds the attribute unnecessarily. for t in tasks: if t.priority > 5: t['status'] = 'urgent' uses dictionary syntax which is invalid. for t in tasks: t.status = 'urgent' if t.priority <= 5: del t.status adds status to all then deletes for low priority, which is inefficient and error-prone.
  3. Final Answer:

    for t in tasks: if t.priority > 5: t.status = 'urgent' -> Option A
  4. Quick Check:

    Use if condition and dot notation to add attributes selectively [OK]
Hint: Add attributes inside if-block with dot notation [OK]
Common Mistakes:
  • Using dictionary syntax on objects
  • Adding attribute to all instances regardless of condition
  • Assigning None instead of skipping attribute