Alternate Constructor from a String

Medium ⏱ 12 min 54% acceptance ★★★★☆ 4.3
Give Order(product, qty) a classmethod factory from_line(cls, line) that parses 'pen x3'-style strings (product, space, x, quantity) into an instance. Factories as classmethods keep parsing logic on the class and play well with subclassing (they receive cls, not a hardcoded name).

Examples

Example 1
Input
o = Order.from_line('pen x3'); (o.product, o.qty)
Output
('pen', 3)
Explanation

The string is parsed and forwarded to the real constructor.

Constraints

  • Use @classmethod and cls(...), not Order(...).
  • Quantity follows the literal 'x'.

Topics

OOPclassmethod

Companies

StripePayPalRazorpay

Hints

Hint 1

line.rsplit(' x', 1) splits product from count.

Hint 2

Return cls(product, int(qty)).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.