runtime
288 / 500
question 288 Advanced OOP & Design · medium

A descriptor that checks codes

SKUs, customer ids and postcodes all follow patterns, and they are checked in many classes. Write a descriptor Matches(pattern) that strips the assigned text, upper-cases it, checks it against the regular expression with re.fullmatch, and stores it, raising ValueError (with the attribute's name in the message) when it doesn't match. Use it in Product for sku ([A-Z]{3}-\d{5}) and in Customer for customer_id (C\d{5}).

DescriptorMatches(pattern) with __set_name__, __get__ (returns itself when read from the class), __set__
Storesthe stripped, upper-cased text
ClassesProduct(sku, name) with sku = Matches(r"[A-Z]{3}-\d{5}"); Customer(customer_id, email) with customer_id = Matches(r"C\d{5}")

Loading your progress…

A descriptor that checks codes — Python practice · Runtime