Creating a class in python


Creating a class in Python involves defining a blueprint for objects.

A class encapsulates data and functions that operate on that data.

Objects are instances of classes, and they can have attributes (data) and methods (functions) that define their behavior.

Creating a Class in Python

To create a class, you use the class keyword followed by the class name and a colon. Here’s a simple example:

class Dog:
    pass

This defines a class named Dog with no attributes or methods.

Now, let's add some properties (attributes) and methods (functions).

Class Attributes and Methods

Attributes are variables that belong to a class, and methods are functions that belong to a class.

class Dog:
    # Class attribute
    species = "Canis familiaris"

    def __init__(self, name, age):
        # Instance attributes
        self.name = name
        self.age = age

    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old."

    # Another instance method
    def speak(self, sound):
        return f"{self.name} says {sound}."

Here - 

  • species is a class attribute shared by all instances of the Dog class.
  • __init__ is a special method called a constructor that initializes each instance with name and age.
  • description and speak are instance methods that operate on the instance data.


Creating Objects

You create an object (an instance of a class) by calling the class as if it were a function

class Dog:
    # Class attribute
    species = "Canis familiaris"

    def __init__(self, name, age):
        # Instance attributes
        self.name = name
        self.age = age

    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old."

    # Another instance method
    def speak(self, sound):
        return f"{self.name} says {sound}."

my_dog = Dog("Buddy", 3)
print(my_dog.description())  # Output: Buddy is 3 years old.
print(my_dog.speak("Woof Woof"))  # Output: Buddy says Woof Woof.


Properties of Class Objects

  • Encapsulation: Class objects can bundle data (attributes) and methods (functions) that operate on the data into a single unit.

  • Inheritance: Classes can inherit attributes and methods from other classes, promoting code reuse.

  • Polymorphism: Different classes can be used interchangeably if they implement the same methods, even if the underlying implementation differs.


Example with Inheritance

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

In this example:

  • Animal is a base class.
  • Dog and Cat are derived classes that inherit from Animal.

Creating objects of Dog and Cat:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak())  # Output: Buddy says Woof!
print(cat.speak())  # Output: Whiskers says Meow!


Summary

  • Class: Blueprint for creating objects (instances).
  • Object: Instance of a class.
  • Attributes: Variables that hold data specific to an object.
  • Methods: Functions that define the behavior of an object.


By using classes, you can create complex programs that are easy to manage and understand.