How to define a method in Python class?

Hello folks, today we are going to discuss defining a method in a Python class. Methods are basically normal functions inside a class.

Defining a method in Python class

Steps:

  • Define a class (ex: CodeSpeedy)
  • Define a method inside the class using the ‘def ‘ keyword
  • Now the methods can be called outside the class using objects

Defining a method

Defining a method consists of two parts:

  • Method Declaration
    • Declaring the name of the method and required parameters
  • Method Body
    • Consists the code to be implemented

Defining a method inside a class is similar to creating a Python function outside the class. Inside the class also, you have to use the def keyword to define a method. A function inside the class is known as the method.

Below is the syntax on how to create a method inside the class:

class ClassName:
  # Defining the method
  def metho_name(parameters):
    # Code block

Using the method from the class

To use a method from the class we need to perform following steps:

  • Declare an object for the class
  • Using the object we can implement the methods inside the class

Let us look into an example:

class CodeSpeedy: #Declaring the class
  def fibanocci(self,n):  #Definig the method
    l = [0,1]  # l is a list
    a = 0
    b = 1
    if n == 1:
      return [0] #Returns [0] as it is the only element which is part of fibanocci sequence less than 1
    if n==2:
      return [0,1] ##Returns [0,1] as they are the only element which is part of fibanocci sequence less than 1
    for i in range(3,n+1):
      if a+b >=n:
        break
      c = a+b
      l.append(c)
      a = b
      b = c
    return l
k=150
object = CodeSpeedy() # Declaring an object for CodeSpeedy class
print(object.fibanocci(k)) #Calling the method

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

We defined a Fibonacci method in the CodeSpeedy class, this method prints the numbers which are in the Fibonacci sequence less than a given number.

Defining methods using other methods from same class

Calling the method from the same class is done by using the “self” keyword. It is explained clearly in the following code.

class CodeSpeedy:

  def square(self,n):#Method for finding square
    return n*n

  def cube(self,n):#Method for finding cube
    return n*n*n
    
  def prints(self,n): #Method for printing square and cube
    print("Square of n is",self.square(n)) #Calling the first method from class
    print("Cube of n is",self.cube(n))   #Calling the second method from class
    return "Used methods from class"

ob = CodeSpeedy() #Decalring an object
print(ob.prints(3))#Calling the method

Output:

Square of n is 9
Cube of n is 27
Used methods from class

Don’t stop learning

Learn more about classes and methods here

Thanks for reading

Leave a Reply

Your email address will not be published.