Overview

In this section, we will learn about class methods:

  • Class methods are methods that are defined inside a class, but they are not associated with any particular object of that class. Class methods can be used to perform operations on the class itself, such as creating new objects or accessing class variables.

What Are Methods in Python Classes?

Methods in Python classes are functions that are nestled within a class. They allow objects created from the class to perform specific actions or calculations. To better understand methods, let's go through some important points:

  • Methods Need Parameters: A fundamental requirement for methods is that they must have at least one parameter. Unlike regular functions, methods are always associated with an object, and this parameter is typically named self. This parameter connects the method to the specific object it's being invoked on.
  • The self Parameter: The self parameter serves as a reference to the instance of the object that the method is acting upon. It's essentially a way for the method to access the object's data and other methods.
  • Creating Objects and Invoking Methods: To create an object from a class and invoke its methods, you treat the class name like a function and store the result in a variable. Then, you can use that variable to call the methods.

Method with No Parameter

In this example, we'll explore how to define a method within a Python class that doesn't take any parameters. We'll create an object from the class and invoke the method to see the output.

Example:

class Coffee:
    def showInfo(self):
        print("I love coffee.")

bev = Coffee()
bev.showInfo()

# Output: I love coffee.

In this simple demonstration, the class named Coffee contains a method called showInfo. Since this method doesn't require any parameters, it's invoked without passing any arguments. The result is the output "I love coffee." showcasing how methods can be defined and used within Python classes.

Passing Parameters to Methods

If you want your methods to accept parameters other than self, you can define additional parameters in the method's definition. When calling the method, you don't need to specify self explicitly.

Example:

class Coffee:
    def showInfo(self, name):
        print("I love coffee, specifically ", name)

drink = Coffee()
drink.showInfo("Latte")

# Output: I love coffee, specifically Latte

Accessing Instance Variables

The self parameter allows you to access both instance variables (variables specific to an object) and class variables (variables shared among all instances of the class).

Example:

class Coffee:
    price = 1.00
    def showInfo(self):
        print(self.name, format(self.price, ".2f"))

drink = Coffee()
drink.name = "Latte"
drink.showInfo()

# Output: Latte 1.00

Invoking Other Methods

You can use the self parameter to call other methods within the class, enabling methods to interact with each other.

Example:

class Coffee:
    def showLove(self):
        print("I love coffee")
    def showLife (self):
        print("Coffee is life")
        self.showLove()

bev = Coffee()
bev.showLife()

# Output: Coffee is life
#	    		I love coffee

Special Method: __init__ Constructor

If you name a method __init__, it becomes a constructor. Constructors are automatically invoked when an object is created from the class. They're used to set up the initial state of the object.

Example:

Mangling a class variable's name has the same effects as those you're already familiar with.

Look at the example below. Can you guess its output?

class Coffee:
    def __init__(self, name):
        self.n = name

drink = Coffee("Latte")
print(drink.n)

# Output: Latte

Constructor with Default Values

You can define a constructor with default parameter values, just like with regular functions.

Example:

class Coffee:
    def __init__(self, name=None):
        self.n = name

drink1 = Coffee("Latte")
drink2 = Coffee()

print(drink1.n)
print(drink2.n)

# Output: Latte
#         None

Private Methods

Methods whose names start with __ are partially hidden, following a concept called name mangling. These methods can still be accessed, but their names are altered to discourage accidental use.

Example:

class Coffee:
    def visible(self):
        print("I see coffee")
    def __hidden(self):
        print("I see no sugar")

drink = Coffee()
drink.visible
#drink.__hidden()         # This will fail
drink._Coffee__hidden()   # This will work

In conclusion, methods are essential tools for defining the behavior of Python classes. They allow objects to perform specific actions, access data, and interact with each other. By understanding the self parameter, constructors, and method naming conventions, you'll be well-equipped to create well-organized and functional classes in Python.