0
0
Pythonprogramming~10 mins

Object lifecycle overview 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 create an object of class Person.

Python
class Person:
    def __init__(self, name):
        self.name = name

p = [1]("Alice")
print(p.name)
Drag options to blanks, or click blank then click option'
APerson
Bobject
Cself
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'object' instead of the class name.
Using 'self' outside the class.
Using 'init' which is a method name, not a class.
2fill in blank
medium

Complete the code to define a destructor method that prints a message when an object is deleted.

Python
class Car:
    def __del__(self):
        print([1])

c = Car()
del c
Drag options to blanks, or click blank then click option'
ACar object deleted
BCar object destroyed
C'Car object deleted'
D'Car object destroyed'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the string message.
Using print without parentheses (Python 3 requires parentheses).
3fill in blank
hard

Fix the error in the code to properly initialize the object with a name attribute.

Python
class Animal:
    def __init__(self, name):
        [1].name = name

pet = Animal("Buddy")
print(pet.name)
Drag options to blanks, or click blank then click option'
AAnimal
Bself
Cthis
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using the class name instead of 'self'.
Using 'this' which is not a Python keyword.
Using the attribute name instead of 'self'.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps each word to its length only if the length is greater than 3.

Python
words = ["apple", "cat", "banana", "dog"]
lengths = {word: [1] for word in words if len(word) [2] 3}
Drag options to blanks, or click blank then click option'
Alen(word)
B>
C<
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the condition.
Using 'word' instead of 'len(word)' for the value.
Not filtering words correctly.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase keys to their values only if the value is greater than 0.

Python
data = {'a': 1, 'b': 0, 'c': 3}
result = { [1]: [2] for k, v in data.items() if v [3] 0 }
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'k' instead of 'k.upper()' for keys.
Using '<' instead of '>' in the condition.
Using 'k' instead of 'v' for values.