Type of variable in OOPS
gaurbprajapati
Posted on August 15, 2023
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:
- 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
-
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
- 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
- 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
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.
💖 💪 🙅 🚩
gaurbprajapati
Posted on August 15, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.