Classes
A class is a blueprint for objects that share the same data and behaviour:
class Dog:
def __init__(self, name):
self.name = name
self.tricks = []
def learn(self, trick):
self.tricks.append(trick)
def __str__(self):
return f"{self.name} knows {len(self.tricks)} tricks"
rex = Dog("Rex")
rex.learn("sit")
print(rex) # Rex knows 1 tricks
__init__runs when you create an object withDog("Rex"). It sets up the object's data.selfis the object itself. Every method takes it as its first parameter.self.name = namestores a value on that particular dog.__str__controls whatprintandstr()show.
Inheritance
A class can build on another, keeping its methods and changing or adding some:
class GuideDog(Dog):
def __init__(self, name, owner):
super().__init__(name) # run Dog's setup first
self.owner = owner
def __str__(self):
return f"{super().__str__()} and guides {self.owner}"
super() reaches the parent class, so you can reuse its code instead of copying it.
Your task
class Productwith:__init__(self, name, price), startingstockat 0,restock(self, quantity),sell(self, quantity): raisesValueErrorif there is not enough stock; otherwise reduces stock and returnsprice * quantity,__str__:"Rice (4 in stock)".
class DiscountedProduct(Product)with an extradiscount(e.g.0.2for 20%), whosesellreturns the discounted total.