Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python Class and Static Methods Code

Practice creating class methods, static methods, and subclass-aware class methods.

~8 min read

Challenge 1

Add a class method that creates an instance from a name in uppercase.

python Your answer
class User:
    def __init__(self, name):
        self.name = name

    

user = User.from_name("mina")
print(user.name)

Press Ctrl⌘Enter to check your answer

Challenge 2

Make is_valid a static method that returns True only for positive integers.

python Your answer
class Order:
    

print(Order.is_valid(5))
print(Order.is_valid(0))

Press Ctrl⌘Enter to check your answer

Challenge 3

Add a class method that constructs the class that calls it, preserving subclass behavior.

python Your answer
class Message:
    def __init__(self, text):
        self.text = text

    

class Alert(Message):
    pass

message = Alert.create("Warning")
print(type(message).__name__)

Press Ctrl⌘Enter to check your answer

Challenge 4

Declare format_code as a static method because it needs no instance or class state.

python Your answer
class Formatter:
    

print(Formatter.format_code(7))

Press Ctrl⌘Enter to check your answer