Adding custom attributes in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we add custom attributes to objects, it is important to know how the time to do this grows as we add more attributes.
We want to understand how the work changes when the number of attributes increases.
Analyze the time complexity of the following code snippet.
class MyObject:
pass
obj = MyObject()
for i in range(n):
setattr(obj, f'attr{i}', i)
This code adds n custom attributes to an object one by one using a loop.
- Primary operation: Adding one attribute to the object using
setattr. - How many times: This operation repeats
ntimes, once for each attribute.
Each new attribute is added one after another, so the total work grows as we add more attributes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 attribute additions |
| 100 | 100 attribute additions |
| 1000 | 1000 attribute additions |
Pattern observation: The work grows directly in proportion to the number of attributes added.
Time Complexity: O(n)
This means the time to add attributes grows linearly with the number of attributes you add.
[X] Wrong: "Adding many attributes is always instant and does not depend on how many there are."
[OK] Correct: Each attribute addition takes some time, so more attributes mean more total time.
Understanding how adding properties to objects scales helps you reason about performance in real programs where objects grow dynamically.
"What if we added all attributes at once using a dictionary update instead of one by one? How would the time complexity change?"
Practice
Solution
Step 1: Understand what attributes are
Attributes are values or properties stored inside an object to hold data or state.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.Final Answer:
Store extra information directly on that object -> Option CQuick Check:
Custom attributes = extra data on object [OK]
- Thinking attributes change the object's type
- Confusing attributes with deleting objects
- Believing attributes restrict object usage
color with value 'red' to an object car?Solution
Step 1: Identify attribute assignment syntax
In Python, attributes are assigned using dot notation: object.attribute = value.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.Final Answer:
car.color = 'red' -> Option AQuick Check:
Use dot notation to add attributes [OK]
- Using dictionary syntax on objects
- Using arrow (->) like in other languages
- Calling attribute as a function
class Dog:
pass
my_dog = Dog()
my_dog.age = 5
print(my_dog.age)Solution
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.Step 2: Print the attribute value
Printing my_dog.age outputs the value stored, which is 5.Final Answer:
5 -> Option DQuick Check:
Custom attribute value prints correctly [OK]
- Expecting class name or attribute name as output
- Thinking attribute does not exist yet
- Confusing attribute with method call
height to an object person:class Person:
def __init__(self, name):
self.name = name
person = Person('Alice')
person.height = 170
print(person['height'])Solution
Step 1: Check how attribute is added
The code correctly adds height using dot notation: person.height = 170.Step 2: Identify incorrect attribute access
Printing uses person['height'], which is dictionary syntax and invalid for normal objects. It should be person.height.Final Answer:
Using person['height'] instead of person.height -> Option BQuick Check:
Access attributes with dot, not brackets [OK]
- Using dictionary syntax on objects
- Thinking attributes must be in __init__
- Believing attributes can't be added later
status to multiple instances of a class Task only if their priority is above 5. Which code correctly does this?Solution
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.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.Final Answer:
for t in tasks: if t.priority > 5: t.status = 'urgent' -> Option AQuick Check:
Use if condition and dot notation to add attributes selectively [OK]
- Using dictionary syntax on objects
- Adding attribute to all instances regardless of condition
- Assigning None instead of skipping attribute
