Menu

Showing posts with label Function in Python. Show all posts
Showing posts with label Function in Python. Show all posts

Difference between function and method in Python

Let’s understand the difference between Python methods and functions and when and how to use function or method:

  1. Functions:

    • Functions are standalone blocks of code that can be called by their name.
    • They are defined independently and are not associated with any specific class or object.
    • Functions can have zero or more parameters.
    • They may or may not return any data.
    • Example of a user-defined function:
      def subtract(a, b):
          return a - b
      
      print(subtract(10, 12))  # Output: -2
      
  2. Methods:

    • Methods are special types of functions associated with a specific class or object.
    • They are defined within a class and are dependent on that class.
    • A method always includes a self parameter (for instance methods) or a cls parameter (for class methods).
    • Methods operate on the data (instance variables) contained by the corresponding class.
    • Example of a user-defined method:
      class ABC:
          def method_abc(self):
              print("I am in method_abc of ABC class.")
      
      class_ref = ABC()  # Create an object of ABC class
      class_ref.method_abc()  # Output: "I am in method_abc of ABC class." 

In final conclusion, functions are independent, while methods are associated with classes or objects. Functions can be called directly by their name, but methods require invoking the class or object they belong to. 

Pyhton Function sample code

Different ways to manage fucntion parameter in Python.

def paragraph(font,background,fontSize,color):
    print('Font:',font,', Background',background,', Font Size',fontSize,', Font Color',color)
    
paragraph('Ariel','red','18px','white')


# Fucntion parameters with default value
def paragraph(font='Monoview',background='grey',fontSize='18px',color='blue'):
    print('Font:',font,', Background:',background,', Font Size:',fontSize,', Font Color:',color)
    
paragraph('Ariel','red','white')


# Fucntion parameters with following the sequence of paramters
def paragraph(font='Monoview',background='grey',fontSize='18px',color='blue'):
    print('Font:',font,', Background:',background,', Font Size:',fontSize,', Font Color:',color)
    
paragraph(color='red',background='orange')

python logo