Introduction to Python Classes

In Python, a class is like a blueprint for creating objects. Imagine you want to create multiple objects that have similar properties and behaviors. A class helps you achieve this by defining the structure and functionality that all objects of that class will share.

What is a Class?

In Python, a class is a blueprint for creating objects (instances). It defines the properties (attributes) and behaviors (methods) that the objects created from the class will have. Classes allow for the organization of code into reusable and structured components. You can define a class using the class keyword, and objects are created by instantiating the class.

class Point:
    x = 0  # class attribute
    y = 0  # class attribute

This code defines a `Point` class with two attributes, 'x' and 'y'. You can create an object from this class and assign values to these attributes like this:

p1 = Point()
p1.x = 2
p1.y = -5
print(p1.x, p1.y)  

# Output: 2 -5

Working with Classes

Working with classes in Python involves defining a class, creating objects (instances), and interacting with the class's attributes and methods.

  1. Defining a Class: You define a class using the class keyword. Inside the class, you can define attributes (variables) and methods (functions).
  2. Creating an Object: You create an object (instance) of a class by calling the class like a function.
  3. Accessing Attributes and Methods: You can access the attributes and methods of the object using dot notation.
  4. Modifying Attributes: You can modify an object's attributes directly.
  5. Inheritance: Classes can inherit from other classes, allowing you to create a hierarchy of classes that share functionality.
    from Point import *
    
    p1 = Point()
    p1.x = 7
    p1.y = -3
    p1.name = "Baibhav Kumar"  # You can add new attributes dynamically
    print(p1.x, p1.y, p1.name)  
    
    # Output: 7 -3 Baibhav Kumar

The 'self' Keyword

The self keyword in Python is used within a class to refer to the instance of the class itself. It allows you to access instance attributes and methods from within the class. When defining methods in a class, the self is passed as the first argument to ensure that the method operates on the specific instance of the class that calls it.

class Dog:
    def __init__(self, name):
        self.name = name  # 'self.name' refers to the instance attribute 'name'

    def bark(self):
        return f"{self.name} barks!"  # 'self.name' refers to the instance's 'name' attribute
  • Self in Methods: In instance methods, the self represents the instance calling the method. It gives access to the attributes and other methods of that particular object.
  • Required as First Parameter: Self must be the first parameter when defining instance methods, although it is not passed explicitly when calling the method.
    my_dog = Dog("Buddy")
    print(my_dog.bark())  # No need to pass 'self', Python handles it internally.
    

Python Class Constructors

In Python, class constructors are special methods that are used to initialize objects when they are created. The constructor is defined using the __init__() method, which is called automatically when a new instance of the class is created. The __init__() method allows you to set up initial values for the object's attributes.

__init__() Method: The constructor method, __init__(), is automatically invoked when you create a new object from a class. It typically takes self as the first parameter, followed by any other parameters needed to initialize the object.

def __init__(self, parameter1, parameter2):
    # Initialization code

An example of a constructor,

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

This constructor initializes the 'x' and 'y' attributes with the values passed when creating an object.

  • Initialization: The constructor is primarily used to set the initial state of an object by initializing its attributes.
  • Automatic Call: You don't call __init__() directly; it runs automatically when you create a new object.
  • Optional Parameters: You can customize constructors to accept optional parameters and set default values.

Defining Methods in a Class

In Python, methods are functions defined within a class that operate on the instances of that class. They are used to define the behaviors of objects created from the class. Methods typically have self as the first parameter, which refers to the instance of the class.

Instance Methods: The most common type of method, which operates on a specific instance of the class. You define them with the self-parameter.

class Point:
    def set_location(self, x, y):
        self.x = x
        self.y = y

    def distance_from_origin(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5

To call these methods, you use the following syntax.

p = Point()
p.set_location(3, -4)
print(p.distance_from_origin())  

# Output: 5.0

Key Points

  • self Parameter: Every instance method must have self as its first parameter. It refers to the instance calling the method and allows access to its attributes and other methods.
  • Calling Methods: When you call a method on an object, you don't need to pass the self-argument. Python automatically passes the instance as the first argument.
  • Additional Parameters: Methods can take additional parameters like regular functions. For example, greet(self, person) takes an additional person parameter.
  • Returning Values: Methods can return values just like functions, allowing the result to be used elsewhere in the program.

Object Functions

Object functions, also known as methods, are functions defined within a class that describe the behaviors or actions that objects (instances) of that class can perform. These methods enable objects to interact with their own data (attributes) and with other objects, making them fundamental to object-oriented programming in Python.

Object functions are defined inside the class using the keyword def. The first parameter of any method is usually self, which points to the instance of the class. Using this self parameter, the method will be able to retrieve and modify the attributes of the object.

class Point:
    def set_location(self, x, y):
        self.x = x
        self.y = y

    def distance_from_origin(self):
        return sqrt(self.x ** 2 + self.y ** 2)

    def distance(self, other):
        dx = self.x - other.x
        dy = self.y - other.y
        return sqrt(dx ** 2 + dy ** 2)

the Point class has three methods: set_location, distance_from_origin, and distance. The distance method calculates the distance between two points.

Using Object Functions

Object functions can be called in two main ways:

  1. Using the object name: This is the most common way to call a method. You simply call the method on the object instance.
  2. Using the class name: This approach is less common but can be useful in certain cases. You call the method on the class itself, passing the object as the first argument.

Calling Functions

In Python, once you define methods (object functions) within a class, you can call these functions to perform actions on the objects (instances) created from the class. Calling functions allows you to utilize the behaviors defined within a class to manipulate and interact with the object's data.

Ways to Call Functions

There are two primary ways to call functions in Python:

  1. Using the Object Name: This is the most common way to call a method. You create an object from the class and then use the dot (.) notation to call the method on that object.
  2. Using the Class Name: In some cases, you might want to call a method by directly using the class name. In this approach, you explicitly pass the object as the first parameter to the method.
p = Point(3, -4)
p.distance(1, 5)  # Using object name

Point.distance(p, 1, 5)  # Using class name

The '__str__' Method

The __str__ method in Python is a special method that provides a human-readable string representation of an object. It's called automatically when you use the print() function or str() on an object. The __str__ method should return a string that gives a meaningful description of the object. This is similar to Java's 'toString()' method.

By overriding the __str__ method in your class, you can define how you want the object to be represented as a string.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"({self.x}, {self.y})"

Now, when you print an object of this class, it will display the custom string format defined in the '__str__' method.

p = Point(3, -4)
print(p)  # Output: (3, -4)

Key Points

  • Custom String Representation: By overriding __str__, you can customize what gets displayed when the object is printed.
  • Readable Output: The string returned by __str__ should be easy for users to read and understand.
  • Automatic Invocation: __str__ is automatically called by print() or str().

Putting It All Together

Let's see a complete example that puts all of these concepts into practice:

from math import sqrt

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def set_location(self, x, y):
        self.x = x
        self.y = y

    def distance_from_origin(self):
        return sqrt(self.x ** 2 + self.y ** 2)

    def distance(self, other):
        dx = self.x - other.x
        dy = self.y - other.y
        return sqrt(dx ** 2 + dy ** 2)

    def __str__(self):
        return f"({self.x}, {self.y})"

p1 = Point(3, -4)
print("Initial:", p1)
print("Distance from Origin:", p1.distance_from_origin())

p2 = Point(-3, 4)
print("Distance from Point (-3, 4):", p1.distance(p2))

This code will create two points and calculate the distance from the origin and between the two points. It also shows how to implement the __str__ method to print out the points in a readable function.

Conclusion

In Python, classes provide a powerful way to structure your code by grouping related data and functionality. With the help of constructors, methods, and the 'self' keyword, you can create objects that encapsulate both state and behavior. Whether you’re building simple applications or complex systems, mastering classes is an essential step in becoming a proficient Python programmer.


Recommended Free Ebook
Similar Articles