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 = "Tyler Durden"  # You can add new attributes dynamically
    print(p1.x, p1.y, p1.name)  
    
    # Output: 7 -3 Tyler Durden

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.

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().

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