0
0
Pythonprogramming~5 mins

Accessing and modifying attributes in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an attribute in a Python class?
An attribute is a variable that belongs to an object or class. It stores information about the object.
Click to reveal answer
beginner
How do you access an attribute of an object in Python?
Use the dot notation: object.attribute. For example, car.color accesses the color attribute of the car object.
Click to reveal answer
beginner
How can you change the value of an attribute in Python?
Assign a new value using dot notation: object.attribute = new_value. This updates the attribute's value.
Click to reveal answer
intermediate
What happens if you try to access an attribute that does not exist?
Python raises an AttributeError because the object does not have that attribute.
Click to reveal answer
intermediate
How can you check if an object has a specific attribute before accessing it?
Use the built-in function hasattr(object, 'attribute'). It returns True if the attribute exists, otherwise False.
Click to reveal answer
How do you access the attribute 'age' of an object 'person'?
Aperson->age
Bperson['age']
Cage.person
Dperson.age
What will happen if you try to access a missing attribute in Python?
AReturns None
BRaises AttributeError
CCreates the attribute automatically
DReturns 0
Which of these changes the value of an attribute 'color' of object 'car' to 'red'?
Acar.color = 'red'
Bcar['color'] = 'red'
Ccolor.car = 'red'
Dsetattr(car, 'color')
How can you safely check if 'height' attribute exists in object 'tree'?
Aif tree['height']:
Bif tree.height:
Cif hasattr(tree, 'height'):
Dif 'height' in tree:
What is the correct way to add a new attribute 'speed' with value 100 to object 'car'?
Acar.speed = 100
Bcar['speed'] = 100
Caddattr(car, 'speed', 100)
Dcar.add('speed', 100)
Explain how to access and modify an attribute of an object in Python.
Think about how you get and set values using the dot.
You got /4 concepts.
    Describe what happens if you try to access an attribute that does not exist and how to avoid errors.
    Consider checking before accessing.
    You got /3 concepts.