Python class Keyword

In Python, the class keyword is used to define a new class. A class is a blueprint for creating objects, allowing us to group related data (attributes) and functions (methods) together. Classes support the principles of Object-Oriented Programming (OOP), such as encapsulation, inheritance, and polymorphism.

Syntax

</>
Copy
class ClassName:
    # Class body
    pass

Defining a Class

To create a class in Python, use the class keyword followed by the class name. Class names are usually written in PascalCase (e.g., Car, Person). The body of the class contains attributes and methods.

Creating Objects

Once a class is defined, we can create objects (instances) of that class. Each object has its own copy of the class attributes and can use the class methods.


Examples

1. Creating a Simple Class and Object

In this example, we define a class named Person with an attribute name. Then, we create an object of this class and assign it a value.

</>
Copy
class Person:
    # Class attribute
    name = "Arjun"

# Creating an object of the class
person1 = Person()

# Accessing the attribute
print(person1.name)

Output:

Arjun

Here, the class Person has an attribute name with a default value of “Arjun”. When we create an object person1, it automatically has this attribute, and we can access it using person1.name.

2. Using the __init__ Method to Initialize Objects

The __init__ method (also known as the constructor) is a special method that runs automatically when an object is created. It is used to initialize object attributes.

</>
Copy
class Person:
    # Constructor method
    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age

# Creating an object with custom values
person1 = Person("Arjun", 25)

# Accessing attributes
print(person1.name)
print(person1.age)

Output:

Arjun
25

Here’s what happens:

  • The __init__ method takes name and age as parameters.
  • When creating an object (person1 = Person("Arjun", 25)), the constructor assigns “Arjun” to self.name and 25 to self.age.
  • These values can be accessed using person1.name and person1.age.

3. Defining and Calling Class Methods

Methods in a class are functions that operate on objects of that class. They must include self as the first parameter.

</>
Copy
class Person:
    def __init__(self, name):
        self.name = name

    # Method to print a greeting
    def greet(self):
        return f"Hello, my name is {self.name}!"

# Creating an object
person1 = Person("Arjun")

# Calling a method
print(person1.greet())

Output:

Hello, my name is Bob!

Explanation:

  • The class Person has a method greet that returns a greeting string.
  • The self parameter allows the method to access the instance’s name attribute.
  • We create an object person1 and call person1.greet() to generate the greeting message.

4. Handling Attribute Errors in Classes

If we try to access an attribute that does not exist, Python raises an AttributeError. Let’s see how to handle this error gracefully.

</>
Copy
class Person:
    def __init__(self, name):
        self.name = name

# Creating an object
person1 = Person("Arjun")

try:
    # Attempting to access a non-existent attribute
    print(person1.age)
except AttributeError as e:
    print("Error:", e)

Output:

Error: 'Person' object has no attribute 'age'

Since we did not define an age attribute for the Person class, Python raises an AttributeError. Using a try-except block helps prevent the program from crashing.