0
0
Pythonprogramming~10 mins

Class attributes in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a class attribute named count initialized to 0.

Python
class MyClass:
    [1] = 0
Drag options to blanks, or click blank then click option'
Aself.count
Bcount
Cdef count
Dinit_count
Attempts:
3 left
💡 Hint
Common Mistakes
Using self.count instead of just count.
Trying to define the attribute inside a method without self.
Using def keyword which is for methods, not attributes.
2fill in blank
medium

Complete the code to access the class attribute count inside the method show_count.

Python
class MyClass:
    count = 5
    def show_count(self):
        print([1])
Drag options to blanks, or click blank then click option'
Aself.count
Bself.count()
Ccount
DMyClass.count
Attempts:
3 left
💡 Hint
Common Mistakes
Using self.count() which tries to call an attribute as a method.
Using just count which is undefined in method scope.
Using self.count which looks for instance attribute, not class attribute.
3fill in blank
hard

Fix the error in the code to correctly increment the class attribute count by 1 inside the method increment.

Python
class MyClass:
    count = 0
    def increment(self):
        MyClass.[1] += 1
Drag options to blanks, or click blank then click option'
Acount
Bself.count
Cincrement
DCount
Attempts:
3 left
💡 Hint
Common Mistakes
Using self.count which may create an instance attribute instead.
Using wrong capitalization like Count.
Trying to call increment as attribute.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps each number to its square, but only for numbers where the class attribute threshold is greater than 5.

Python
class Numbers:
    threshold = 5
    squares = {x: x[1]2 for x in range(1, 6) if x [2] threshold}
Drag options to blanks, or click blank then click option'
A**
B>
C<
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using * instead of ** for power.
Using wrong comparison operator like > instead of <.
Not using the class attribute threshold correctly.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase keys to values, but only include items where the value is greater than 10.

Python
class Data:
    items = {'a': 5, 'b': 15, 'c': 20}
    filtered = [1]: [2] for [3], v in items.items() if v > 10}
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
Ck
Ditems
Attempts:
3 left
💡 Hint
Common Mistakes
Using items instead of k in the loop.
Not converting keys to uppercase.
Swapping keys and values in the comprehension.