Python: Class and Object

Define a Class

class Product:
    def someMethod(self):
        print("Some method called from the Product class")
        
        
my_product = Product()
my_product.someMethod()

print("Object id: ", id(my_product))
Python

Output:

Some method called from the Product class

Object id:  3132832848720
Plaintext

Add __init__ to Class

class Product:
    def __init__(self):
        print("Product class initiated")
        
    def someMethod(self):
        print("Some method called from the Product class")
        
        
my_product = Product()
my_product.someMethod()
Python

Output:

Product class initiated
Some method called from the Product class
Plaintext

Add Properties to Class

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price
        
    def printDetails(self):
        print("Name:", self.name)
        print("Price:", self.price)
        
        
my_product = Product("Sonic Wireless Headphone", 99.99)
my_product.printDetails()
Python

Output:

Name: Sonic Wireless Headphone
Price: 99.99
Plaintext

Leave a Comment


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