Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Define a class in Python

In this tutorial, we will walk through the process of defining a class in Python. A class is a blueprint for creating objects that can have properties (attributes) and behaviors (methods).

Example: Defining a Class

Let's create a class called Student with the following attributes and methods:

  1. Attributes: name and age
  2. Methods: __init__() (constructor), study(), and introduce()
class Student:
    # Class constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method for studying
    def study(self, subject):
        print(f"{self.name} is studying {subject}")

    # Instance method for introducing the student
    def introduce(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

In this example, we define the Student class with the following components:

  1. The __init__() method is the constructor that initializes the name and age attributes of the class. It is called when you create a new instance of the class.
  2. The study() method is an instance method that takes a subject argument and prints a message about the student studying the subject.
  3. The introduce() method is an instance method that prints a message introducing the student.

Creating Instances of the Class

To create instances of the Student class, follow these steps:

  1. Call the class name with the required arguments for the constructor.
  2. Assign the resulting object to a variable.
# Create instances of the Student class
student1 = Student("Alice", 20)
student2 = Student("Bob", 22)

# Call the introduce() method for each student
student1.introduce()  # Output: Hello, my name is Alice and I am 20 years old.
student2.introduce()  # Output: Hello, my name is Bob and I am 22 years old.

# Call the study() method for each student
student1.study("Mathematics")  # Output: Alice is studying Mathematics
student2.study("Physics")  # Output: Bob is studying Physics

In this example, we create two instances of the Student class, student1 and student2, with different name and age attributes. We then call the introduce() and study() methods for each student.

In conclusion, defining a class in Python involves creating a blueprint for objects with attributes and methods. Classes allow you to create objects with specific properties and behaviors, making it easier to organize and manage your code.

  1. Constructor and __init__() method in Python class:

    • Description: The constructor is a special method (__init__) used for initializing instance variables when an object is created.
    • Code:
      class MyClass:
          def __init__(self, attribute):
              self.instance_variable = attribute
      
  2. Adding instance variables to a Python class:

    • Description: Instance variables are added within methods using the self keyword.
    • Code:
      class MyClass:
          def __init__(self, attribute1, attribute2):
              self.variable1 = attribute1
              self.variable2 = attribute2
      
  3. Creating and using class methods in Python:

    • Description: Class methods are defined using the @classmethod decorator and have access to the class itself rather than instances.
    • Code:
      class MyClass:
          class_variable = "I am a class variable"
      
          @classmethod
          def my_class_method(cls):
              print(cls.class_variable)
      
  4. Inheritance and polymorphism in Python classes:

    • Description: Inheritance allows a class to inherit attributes and methods from another class. Polymorphism enables objects of different classes to be used interchangeably.
    • Code:
      class Animal:
          def speak(self):
              pass
      
      class Dog(Animal):
          def speak(self):
              print("Woof!")
      
      class Cat(Animal):
          def speak(self):
              print("Meow!")
      
      def animal_sound(animal):
          animal.speak()
      
      dog = Dog()
      cat = Cat()
      
      animal_sound(dog)  # Output: Woof!
      animal_sound(cat)  # Output: Meow!
      
  5. Encapsulation and private members in Python class:

    • Description: Encapsulation restricts access to certain attributes or methods. Private members are indicated with a double leading underscore.
    • Code:
      class MyClass:
          def __init__(self, public_var, private_var):
              self.public_var = public_var
              self.__private_var = private_var
      
  6. Class-level and instance-level attributes in Python:

    • Description: Class-level attributes are shared among all instances. Instance-level attributes are unique to each instance.
    • Code:
      class MyClass:
          class_variable = "I am a class variable"
      
          def __init__(self, instance_variable):
              self.instance_variable = instance_variable