Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Tuesday, April 16, 2024

Program to illustrate the concept of class and objects in python.

 Code:

class Dog:

    # Class variable

    species = "BULL DOG"


    # Constructor or initializer method

    def __init__(self, name, age):

        # Instance variables

        self.name = name

        self.age = age


    # Instance method

    def bark(self):

        return "Woof!"


# Creating objects (instances) of the Dog class

dog1 = Dog(name="Buddy", age=2)

dog2 = Dog(name="Max", age=3)


# Accessing attributes and calling methods of the objects

print(f"{dog1.name} is {dog1.age} years old.")

print(f"{dog2.name} is {dog2.age} years old.")


print(f"{dog1.name} says: {dog1.bark()}")

print(f"{dog2.name} says: {dog2.bark()}")


# Accessing class variable

print(f"They both belong to the species {Dog.species}.")


Output:






No comments:

Post a Comment