In Python, instance variables, static variables, and local variables are all different types of variables that serve different purposes within a program.
- 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 theself
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.
- 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.
- 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
Post a Comment