Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python __new__ and Object Creation Code

Practice the creation order, subclass-aware __new__(), immutable-value construction, and the boundary where __init__ is skipped.

Advanced ~8 min read

Challenge 1

Create and return the instance using the parent implementation.

python Your answer
class User:
    def __new__(cls, name):
        

user = User("Mina")
print(type(user).__name__)

Press Ctrl⌘Enter to check your answer

Challenge 2

Normalize the string value before the immutable object is created.

python Your answer
class CleanText(str):
    def __new__(cls, value):
        cleaned = value.strip().lower()
        

text = CleanText("  READY  ")
print(text)

Press Ctrl⌘Enter to check your answer

Challenge 3

Return an instance that keeps the actual subclass type.

python Your answer
class Code(str):
    def __new__(cls, value):
        value = value.strip()
        return super().__new__(, value)

class ShortCode(Code):
    pass

print(type(ShortCode(" A7 ")).__name__)

Press Ctrl⌘Enter to check your answer

Challenge 4

Return a string so Token.__init__() is not called.

python Your answer
class Token:
    def __new__(cls, value):
        

    def __init__(self, value):
        raise RuntimeError("Token.__init__ should not run")

result = Token(42)
print(result, type(result).__name__)

Press Ctrl⌘Enter to check your answer