0
0
Pythonprogramming~5 mins

Class attributes in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a class attribute in Python?
A class attribute is a variable that is shared by all instances of a class. It is defined inside the class but outside any instance methods.
Click to reveal answer
beginner
How do class attributes differ from instance attributes?
Class attributes are shared by all instances of the class, while instance attributes belong to each individual object and can have different values.
Click to reveal answer
beginner
Given this code:<br><pre>class Dog:
    species = 'Canis familiaris'
    def __init__(self, name):
        self.name = name</pre><br>What is <code>species</code> here?
<code>species</code> is a class attribute. It is shared by all Dog objects and holds the value 'Canis familiaris'.
Click to reveal answer
intermediate
Can you change a class attribute value for all instances? How?
Yes, by assigning a new value to the class attribute using the class name, e.g., <code>ClassName.attribute = new_value</code>. This changes it for all instances that don't override it.
Click to reveal answer
intermediate
What happens if you assign a value to a class attribute name using an instance?
Assigning a value to a class attribute name via an instance creates or changes an instance attribute with the same name, which hides the class attribute for that instance only.
Click to reveal answer
Where are class attributes defined in Python?
AInside the class but outside any methods
BInside instance methods only
COutside the class definition
DInside the __init__ method only
What is shared by all instances of a class?
AInstance attributes
BLocal variables
CClass attributes
DFunction parameters
If you change a class attribute using the class name, what happens?
AAll instances see the updated value unless they have an instance attribute with the same name
BOnly the first instance changes
CNothing changes for any instance
DOnly new instances get the change
What happens if you assign a value to a class attribute name using an instance?
AThe class attribute changes for all instances
BAn instance attribute is created or updated, hiding the class attribute for that instance
CAn error occurs
DThe class attribute is deleted
Which of these is a correct way to access a class attribute?
AClassName.__init__()
Binstance.attribute()
Cinstance.__init__()
DClassName.attribute
Explain what a class attribute is and how it differs from an instance attribute.
Think about a property all objects share versus something unique to each.
You got /4 concepts.
    Describe what happens when you assign a value to a class attribute name using an instance.
    Consider how Python handles attribute lookup and shadowing.
    You got /3 concepts.