Python: Method Overriding

class Product:
    def __init__(self, name, price, category):
        self.name = name
        self.price = price
        self.category = category
        
    def printDetails(self):
        print("Name:", self.name)
        print("Price:", self.price)
        print("Category:", self.category)
        
class Headphone(Product):
    pass
        
my_product1 = Headphone("Sonic Wireless SWH-30G21", 99.99, "Headphone")
my_product2 = Headphone("Aqua Pro X500", 99.99, "Headphone")

my_product1.printDetails()
my_product2.printDetails()
Python

Output:

Name: Sonic Wireless SWH-30G21
Price: 99.99
Category: Headphone
Name: Aqua Pro X500
Price: 99.99
Category: Headphone
Plaintext
class Product:
    def __init__(self, name, price, category):
        self.name = name
        self.price = price
        self.category = category
        
    def printDetails(self):
        print("Name:", self.name)
        print("Price:", self.price)
        print("Category:", self.category)
        
class Headphone(Product):
    def printDetails(self):
        print("--Headphone details--")
        super().printDetails()
        
my_product1 = Headphone("Sonic Wireless SWH-30G21", 99.99, "Headphone")
my_product2 = Headphone("Aqua Pro X500", 99.99, "Headphone")

my_product1.printDetails()
my_product2.printDetails()
Python

Output:

--Headphone details--
Name: Sonic Wireless SWH-30G21
Price: 99.99
Category: Headphone

--Headphone details--
Name: Aqua Pro X500
Price: 99.99
Category: Headphone
Plaintext
class Product:
    def __init__(self, name, price, category):
        self.name = name
        self.price = price
        self.category = category
        
    def printDetails(self):
        print("Name:", self.name)
        print("Price:", self.price)
        print("Category:", self.category)
        
class Headphone(Product):
    def __init__(self, name, price, category, model, speaker, range):
        self.name = name
        self.price = price
        self.category = category
        self.model = model
        self.speaker = speaker
        self.range = range
            
    def printDetails(self):
        print("--Headphone details--")
        print("Name:", self.name)
        print("Price:", self.price)
        print("Category:", self.category)
        print("Model:", self.model)
        print("Speaker:", self.speaker)
        print("Range:", self.range)
        
my_product1 = Headphone("Sonic Wireless", 99.99, "Headphone", "SWH-30G21", "33mm", "100m")
my_product2 = Headphone("Aqua Pro", 99.99, "Headphone", "X500", "24mm", "10m")

my_product1.printDetails()
my_product2.printDetails()
Python

Output:

--Headphone details--
Name: Sonic Wireless
Price: 99.99
Category: Headphone
Model: SWH-30G21
Speaker: 33mm
Range: 100m

--Headphone details--
Name: Aqua Pro
Price: 99.99
Category: Headphone
Model: X500
Speaker: 24mm
Range: 10m
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.