DEV Community

gaurbprajapati
gaurbprajapati

Posted on

Type of variable in OOPS

In object-oriented programming (OOP), variables can be categorized into different types based on their scope and usage within a class. Here are the main types of variables in OOP:

  1. Instance Variables (Non-Static Variables): Instance variables are associated with individual instances (objects) of a class. Each object has its own copy of these variables. They are defined within the class but outside of any method. Instance variables represent the state of an object and can have different values for different instances of the class.

Example:

   class Person:
       def __init__(self, name, age):
           self.name = name  # instance variable
           self.age = age    # instance variable
Enter fullscreen mode Exit fullscreen mode
  1. Class Variables (Static Variables): Class variables are shared among all instances of a class. They are declared within the class and outside of any method using the @classmethod decorator or directly under the class definition. Class variables are used to represent attributes that are common to all instances of the class.

Example:

   class Circle:
       pi = 3.14159  # class variable
       def __init__(self, radius):
           self.radius = radius  # instance variable
Enter fullscreen mode Exit fullscreen mode
  1. Local Variables: Local variables are defined within a method and have scope only within that method. They cannot be accessed from outside the method. These variables are temporary and exist only during the execution of the method.

Example:

   class Calculator:
       def add(self, x, y):
           result = x + y  # local variable
           return result
Enter fullscreen mode Exit fullscreen mode
  1. Parameter Variables: Parameter variables are used to pass values to methods or constructors. They are placeholders for the values that will be provided when the method is called or the object is created.

Example:

   class Rectangle:
       def __init__(self, width, height):
           self.width = width      # instance variable
           self.height = height    # instance variable
Enter fullscreen mode Exit fullscreen mode

It's important to note that the terminology can vary slightly between programming languages, but the underlying concepts remain consistent. Understanding the different types of variables and their scopes is crucial for writing effective and maintainable object-oriented code.

Top comments (0)