top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Class in Python

Introduction

In this tutorial, we navigate the intricacies of the Class in Python, a cornerstone of object-oriented programming (OOP). As professionals keen on advancing your Python prowess, understanding classes will enhance your efficiency in encapsulating data and leveraging method functionalities.

Overview

Class in Python forms the cornerstone of object-oriented programming, promoting structured and modular code. By defining attributes and methods within a class, developers can simulate real-world entities, creating a more intuitive coding environment. As classes encapsulate data and provide clear interfaces for data interaction, they significantly enhance code clarity and maintainability.

Python’s concise syntax, in contrast with many other programming languages, facilitates faster class implementation without compromising functionality. This has led to Python becoming a preferred choice for many developers venturing into object-oriented design, enabling them to model complex systems efficiently, from software frameworks to interactive applications.

What is a Class in Python?

Class in Python functions as a blueprint or template, pivotal for the creation of objects. These objects are representative of both data essential for an application and the methods to effectively manipulate this data. The fundamental purpose of classes revolves around data encapsulation. This ensures that data is not only aggregated but also protected, offering a systematic means for data portrayal and interaction. 

A class comprises two main components. First, we have attributes, which are essentially variables housed within the class to store data. For instance, consider a 'Car' class; it might possess attributes such as color and brand. 

Secondly, there are methods, which are functions associated with the class that outline the feasible operations on its data. Drawing from the 'Car' example, it might incorporate methods like drive() or park(). Python's approach to class creation is distinguished by its simplicity and efficiency. Merely deploying the ‘class’ keyword is sufficient to establish and instantiate a class. After delineating a class, it can be instantiated repetitively, resulting in the generation of varied objects.

Additionally, Python’s object-oriented nature extends support for inheritance in classes, permitting one class to adopt attributes and methods from another. This, coupled with polymorphism, guarantees a class’s capability to adjust and employ methods inherited from its predecessor, fostering heightened code reusability.

Creating Class in Python Example

Code:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def say_hello(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Create instances of the class
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Access attributes and call methods
print(person1.name)  # Output: Alice
person2.say_hello()  # Output: Hello, my name is Bob and I am 25 years old.

Explanation:

  • You define the Person class with:

    • An __init__ method: This is a constructor method that initializes the attributes name and age when a new instance of the Person class is created.
    • A say_hello method: This method prints a message containing the person's name and age.
  • You create two instances of the Person class:
    • person1 is an instance of a person named "Alice" with an age of 30.
    • person2 is an instance of a person named "Bob" with an age of 25.
  • You access the attributes and call methods of these instances:
    • person1.name retrieves the name attribute of person1, which is "Alice," and prints it.
    • person2.say_hello() calls the say_hello method of person2, which prints a message indicating that Bob is 25 years old.

What is an Object in Python?

In Python, an object is a fundamental concept in object-oriented programming (OOP). Objects are instances of classes, and they encapsulate both data (attributes) and behavior (methods).

Here’s the explanation of an object in Python:

  • An object is a concrete instance of a class. It is created based on the blueprint provided by the class.

  • Objects have attributes, which are variables that store data specific to each instance of the class.

  • Objects also have methods, which are functions defined within the class and operate on the object's attributes.

  • Each object created from a class can have its own unique set of attribute values.

Code:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def say_hello(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Create instances of the class
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Access attributes and call methods
print(person1.name)  # Output: Alice
person2.say_hello()  # Output: Hello, my name is Bob and I am 25 years old.

In this example, person1 and person2 are objects of the Person class. They have attributes (name and age) and can call the say_hello method. Each object represents a distinct instance of a person with its own data. This is a fundamental concept in Python's object-oriented programming paradigm.

Instantiating a Class or Declaring Class Objects in Python 

Instantiating a class in Python means creating an object (also called an instance) based on the blueprint or template defined by a class. When you instantiate a class, you're essentially creating a concrete representation of that class, complete with its attributes and methods. Here's what instantiating a class means in Python:

1.  Class Definition: First, you define a class in your Python code. A class serves as a blueprint that specifies the structure, attributes, and methods that objects created from that class will have.

class MyClass:

    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2

In this example, MyClass is a class definition with an __init__ method that initializes two attributes, param1 and param2.

2. Instantiation: To create an object of the class, you instantiate it by calling the class name as if it were a function, passing any required arguments to the constructor (usually the __init__ method). This process is called instantiation.

obj1 = MyClass(value1, value2)
  • obj1 is the name of the object (an instance of the class).

  • MyClass is the class being instantiated.

  • value1 and value2 are the values passed as arguments to the class's constructor (__init__ method).

3. Object Creation: The line of code above creates an object (obj1) of the MyClass class with the specified attribute values (value1 and value2). This object is now an instance of the class and has access to its attributes and methods.

obj2 = MyClass(another_value1, another_value2)

You can create multiple objects (instances) from the same class with different attribute values, as needed.

In summary, instantiating a class in Python involves creating objects or instances of that class. Each object has its own set of attributes and can execute the methods defined within the class. This is a fundamental concept of object-oriented programming (OOP) and allows you to model real-world entities and their behaviors in a structured and modular way.

Self Parameter in Python

In Python, the self parameter is a special parameter used in the definition of methods within a class. It represents the instance of the class itself and is automatically passed as the first argument to instance methods when they are called. You can name this parameter anything you like, but by convention, it is named self to make the code more readable and consistent.

Here are the key points to understand about the self parameter:

1. self Represents the Instance:

  • In Python, self is used inside instance methods to refer to the object or instance of the class on which the method is called.

  • It allows you to access and manipulate the attributes and methods of the instance within the method.

2. Automatic Passing:

  • When you call an instance method on an object, you don't need to explicitly pass the self argument; Python does it for you automatically.

  • For example, if you have a method my_method defined in a class, when you call obj.my_method(), self inside my_method refers to obj.

3. Naming Convention:

  • Although you can technically use any valid variable name for the self parameter, it's a strong convention in Python to use self to make the code more readable and maintainable.

  • Using self helps indicate that the parameter is referring to the instance itself.

Here's an example to illustrate the use of the self parameter in a class:

Code:

class MyClass:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2
    def my_method(self):
        print(f"This is a method. attribute1: {self.attribute1}, attribute2: {self.attribute2}")
# Creating an instance of MyClass
obj = MyClass("value1", "value2")
# Calling the instance method
obj.my_method()

In this example, self is used within the __init__ method to set the object's attributes (attribute1 and attribute2). It is also used within the my_method method to access and print the attribute values when the method is called on the object obj. Python automatically handles the passing of self when you call the method.

Pass Statement in Python

In Python, the pass statement is a placeholder or a no-operation statement. It is used when syntactically some code is required (for example, inside a function or a class), but you don't want to execute any specific instructions. The pass statement serves as a way to have a valid code block without any actual functionality. It's often used as a temporary placeholder when you're writing code and plan to implement the functionality later.

Here are some common use cases for the pass statement:

1. Function or Method Definitions: When you define a function or method but haven't implemented its functionality yet, you can use pass as a placeholder.

def my_function():
    pass

2. Empty Code Blocks: Sometimes, you might have a conditional statement or loop that doesn't require any action in one branch. You can use pass to indicate that there's no specific action to be taken.

if condition:
    # No action needed for this branch
    pass
else:
    # Perform some action here

3. Class Definitions: When defining a class that you plan to implement later, you can use pass inside the class body.

class MyClass:
    def method1(self):
        pass
    def method2(self):
        pass

4. Creating Minimal Code Structure: When you're sketching out the structure of your code and want to ensure that it's syntactically correct, you can use pass as a placeholder until you fill in the actual code.

The pass statement is essentially a way to satisfy Python's syntax requirements without introducing any functional code. It's helpful during development when you're building the structure of your program and plan to add the actual functionality later.

__init__() Method

Code:

class Per:
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hi, I am', self.name)
x = Per('upGrad!!!')
x.say_hi()

__str__() method 

Code:

class upGrad:
def __init__(self, name, company):
self.name = name
self.company = company
def __str__(self):
return f"My name is {self.name} and I work in {self.company}."
obj = upGrad("Amit", "upGrad!!")
print(obj)

Class and Instance Variables in Python

Code:

class MyClass:
    # Class variable
    class_variable = "I am a class variable"
    def __init__(self, instance_variable):
        # Instance variable
        self.instance_variable = instance_variable
# Create instances of MyClass
obj1 = MyClass("Instance 1")
obj2 = MyClass("Instance 2")
# Access class variable (shared among all instances)
print(obj1.class_variable)  # Output: I am a class variable
print(obj2.class_variable)  # Output: I am a class variable
# Access instance variables (unique to each instance)
print(obj1.instance_variable)  # Output: Instance 1
print(obj2.instance_variable)  # Output: Instance 2
# Modify instance variables
obj1.instance_variable = "New Instance 1"
print(obj1.instance_variable)  # Output: New Instance 1

Conclusion

Mastering the concept of classes in Python is pivotal for any developer keen on harnessing the power of object-oriented programming. The ability to encapsulate data and functions within organized structures not only ensures code efficiency but also boosts its readability and scalability.

As you embark on this journey to delve deeper into Python, consider elevating your learning experience. upGrad offers comprehensive courses tailored for professionals like you, emphasizing practical knowledge and industry relevance.

FAQs

1. What is a class in Python?

A class in Python provides a blueprint for creating objects, encapsulating both data attributes and methods that operate on the data.

2. How to create a class in Python?

Creating classes in Python is not complex. Begin with the class keyword, followed by the class name. Subsequently, define its attributes and methods, ensuring proper indentation.

3. How are classes and objects in Python distinguished?

A class acts as a blueprint detailing properties and behaviors. Conversely, an object is a specific instance of a class, representing those defined properties and behaviors.

4. Do Python classes inherently connect to an object?

Indeed, every class in Python has an associated 'class object', essentially an instance of the class itself.

5. Could you elucidate the role of the __init__ method in Python classes?

Acting as Python's constructor, the __init__ method is invoked upon object creation. It initializes the object's attributes, setting the stage for its operations.

Leave a Reply

Your email address will not be published. Required fields are marked *