0
0
Pythonprogramming~5 mins

Adding custom attributes in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a custom attribute in Python?
A custom attribute is a user-defined variable attached to an object or class to store extra information beyond built-in attributes.
Click to reveal answer
beginner
How do you add a custom attribute to an existing object in Python?
You assign a value to a new attribute name using dot notation, like object.new_attribute = value.
Click to reveal answer
intermediate
Can you add custom attributes to built-in types like int or str?
No, built-in types like int or str do not allow adding custom attributes directly because they are immutable and don't have a writable __dict__.
Click to reveal answer
intermediate
What is the difference between adding custom attributes to an instance vs. a class?
Adding to an instance affects only that object, while adding to a class affects all instances of that class unless overridden.
Click to reveal answer
beginner
Show a simple example of adding a custom attribute to a class instance.
Example:<br><pre>class Dog:
    pass

my_dog = Dog()
my_dog.age = 5  # custom attribute
print(my_dog.age)  # Output: 5</pre>
Click to reveal answer
How do you add a custom attribute named 'color' with value 'red' to an object 'car'?
Acar['color'] = 'red'
Bcar.color = 'red'
Ccar.add_attribute('color', 'red')
Dsetattr(car, 'color')
Which of these can you NOT add custom attributes to directly?
AUser-defined class instances
BObjects created from classes
CCustom classes
DBuilt-in types like int
What happens if you add a custom attribute to a class?
AAll instances of the class get the attribute unless overridden
BThe attribute is deleted from instances
COnly that class instance gets the attribute
DIt raises an error
Which function can also add attributes dynamically to an object?
Adelattr()
Bgetattr()
Csetattr()
Dhasattr()
If you add an attribute to an instance, can it override a class attribute with the same name?
AYes, instance attribute overrides class attribute
BNo, class attribute always takes precedence
COnly if you delete the class attribute first
DIt causes an error
Explain how to add a custom attribute to a Python object and what happens when you add it to a class instead.
Think about the difference between instance and class level.
You got /4 concepts.
    Describe why you cannot add custom attributes to built-in types like int or str in Python.
    Consider how built-in types are implemented.
    You got /3 concepts.