Skip to main content

Python: Explain different types of methods with examples.

In Python, there are several types of methods that can be defined within a class. Each type of method serves a specific purpose and has different characteristics. The common types of methods in Python are:

  1. Instance Methods: Instance methods are the most commonly used methods in Python classes. They are defined within a class and are intended to operate on individual instances of the class. Instance methods have access to the instance variables and can modify their values.

Here's an example that demonstrates an instance method:

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def calculate_area(self):
        return 3.14159 * self.radius ** 2

circle = Circle(5)
print(circle.calculate_area())   # Output: 78.53975

In the above example, the calculate_area() method is an instance method that calculates the area of a circle based on its radius. It uses the instance variable self.radius to perform the calculation.

  1. Class Methods: Class methods are defined using the @classmethod decorator. They operate on the class itself rather than instances of the class. Class methods have access to the class's static variables, but not to the instance variables. They are often used to perform operations that involve the class as a whole.

Here's an example that demonstrates a class method:

class Circle:
    pi = 3.14159

    def __init__(self, radius):
        self.radius = radius

    @classmethod
    def print_pi(cls):
        print(cls.pi)

Circle.print_pi()   # Output: 3.14159

In the above example, the print_pi() method is a class method that prints the value of the static variable pi. It uses the cls parameter to refer to the class itself.

  1. Static Methods: Static methods are defined using the @staticmethod decorator. They are independent of the class and its instances. Static methods do not have access to either instance variables or static variables. They are commonly used for utility functions that don't depend on the state of the class or its instances.

Here's an example that demonstrates a static method:

class MathUtils:
    @staticmethod
    def add_numbers(x, y):
        return x + y

result = MathUtils.add_numbers(5, 10)
print(result)   # Output: 15

In the above example, the add_numbers() method is a static method that simply adds two numbers together. It doesn't require any class instances or variables.

  1. Special Methods (Magic Methods): Special methods, also known as magic methods or dunder methods, have double underscores (__) at the beginning and end of their names. They define how instances of a class should behave in certain situations, such as when they are created, compared, or printed. Special methods are automatically invoked by Python in response to specific operations.

Here's an example that demonstrates a special method:

class Person:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"Person: {self.name}"

person = Person("Alice")
print(person)   # Output: Person: Alice

In the above example, the __str__() method is a special method that defines how instances of the Person class should be represented as strings when using the print() function.

Comments

Popular Posts

List of latest and most asked PHP practical interviews questions & answers

Core PHP Practical Interview Questions In this blog post I am sharing a list of some most asked PHP interview questions & answers. These are very useful and helpful for the freshers and experienced developer too. I have taken these questions from different sources and listed here at one place. Ques. How to reverse a string without using any builtin function? Ans: <?php $str = 'My name is Diwakar Kumar'; $len = 0; while(isset($str[$len]) != '') $len++; for($i = $len ; $i >= 0 ; $i--) { echo @$str[$i]; } Ques: Write a function to check if a given string is a palindrome or not. Ans: 1st Method: <?php function isPalindrome($str) { $str = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str)); // Convert to lowercase and remove non-alphanumeric characters $reverse = strrev($str); // Reverse the string return $str === $reverse; // Compare original and reversed string } 2nd Method: <?php funct

Bootstrap Responsive Media Queries CSS Tips

AS a developer I faces lots of problem while making website responsive to make website visible correctly on all devices like mobile, tablet and desktop. So, today I am sharing some Bootstrap responsive CSS styles and Media Queries  tips with you. But make sure that you are not repeating the same media queries for the same screen size. Otherwise it will override your previous CSS style rules.    The Grid Sizes .col-xs-$ => Extra Small (Phones Less than 768px) .col-sm-$ => Small Devices (Tablets 768px and Up) .col-md-$ => Medium Devices (Desktops 992px and Up) .col-lg-$  => Large Devices (Large Desktops 1200px and Up) Here is the Responsive CSS Style for all Screen Sizes Read more: https://scotch.io/tutorials/default-sizes-for-twitter-bootstraps-media-queries

How to take user input from terminal(stdin) in Rust?

In Rust, you can use the std::io module from the standard library to read input from the user. Here's an example that demonstrates how to get input from the user: use std::io; fn main() { // Create a new instance of `std::io::stdin` for reading user input let mut input = String::new(); // Prompt the user for input println!("Enter your name:"); // Read input from the user io::stdin() .read_line(&mut input) .expect("Failed to read line"); // Trim any trailing whitespace or newlines from the input let name = input.trim(); // Display the user's input println!("Hello, {}!", name); } In this example, we create a mutable String variable named input to store the user's input. We then use the std::io::stdin() function to obtain a handle to the standard input stream. Next, we call the read_line() method on the input stream, passing a mutable reference to the input variable. The r