Skip to main content

Different types of variables in Python with examples.

In Python, instance variables, static variables, and local variables are all different types of variables that serve different purposes within a program.

  1. Instance Variables: Instance variables are unique to each instance of a class. They are defined within a class's methods or the __init__ method and are accessed using the self keyword. Each instance of a class maintains its own copy of instance variables. These variables hold data specific to each object and can have different values for each instance of the class.

Here's an example that demonstrates instance variables:


class Person:
    def __init__(self, name, age):
        self.name = name    # instance variable
        self.age = age      # instance variable

person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

print(person1.name)   # Output: Alice
print(person2.name)   # Output: Bob
print(person1.age)    # Output: 25
print(person2.age)    # Output: 30 

In the example above, name and age are instance variables specific to each instance of the Person class.

  1. Static Variables: Static variables, also known as class variables, are shared among all instances of a class. They are defined within a class but outside of any class methods. Static variables are accessed using the class name itself or an instance of the class. Any modifications made to a static variable will be visible to all instances of the class.

Here's an example that demonstrates static variables:


class Circle:
	'''
	Static Variable example
	'''
    pi = 3.14159   # static variable

    def __init__(self, radius):
        self.radius = radius    # instance variable

circle1 = Circle(5)
circle2 = Circle(10)

print(circle1.radius)   # Output: 5
print(circle2.radius)   # Output: 10
print(Circle.pi)        # Output: 3.14159
print(circle1.pi)       # Output: 3.14159
print(circle2.pi)       # Output: 3.14159

Circle.pi = 3.14       # Modifying the static variable

print(Circle.pi)       # Output: 3.14
print(circle1.pi)      # Output: 3.14
print(circle2.pi)      # Output: 3.14 

In the above example, pi is a static variable shared among all instances of the Circle class. It holds a common value for all circles, and any modification to it affects all instances.

  1. Local Variables: Local variables are defined within a specific block of code, such as a function or a method. They have a limited scope and are only accessible within that block. Once the block is exited, the local variable is no longer accessible.

Here's an example that demonstrates local variables:


def greet(name):
    message = "Hello, " + name    # local variable
    print(message)

greet("Alice")   # Output: Hello, Alice

print(message)   # Error: NameError: name 'message' is not defined 

In the above example, message is a local variable defined within the greet function. It is accessible only within the function and not outside of it.

To summarize:

  • Instance variables are specific to each instance of a class.
  • Static variables are shared among all instances of a class.
  • Local variables are limited to the scope of a specific block of code, such as a 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