Understanding Class and Instance Variables in Python 3
Understanding Class and Instance Variables in Python 3
Python 3 is an object-oriented programming language that supports the concept of classes and objects. In this tutorial, we will learn about class and instance variables in Python 3.
Class Variables
Class variables are variables that are shared among all instances of a class. They are defined inside the class definition and outside any method. A class variable can be accessed using the class name or any instance of the class.
Here is an example:
class Car: color = 'red' car1 = Car() car2 = Car() print(car1.color) # Output: red print(car2.color) # Output: red Car.color = 'blue' print(car1.color) # Output: blue print(car2.color) # Output: blue
In the above example, we defined a class variable "color" inside the Car class. We then created two instances of the Car class and accessed the "color" variable using the instances. Finally, we changed the value of the "color" variable using the class name and accessed it again using the instances.
Instance Variables
Instance variables are variables that belong to an instance of a class. They are defined inside the class methods using the "self" keyword. An instance variable can only be accessed using an instance of the class.
Here is an example:
class Car:
def __init__(self, color):
self.color = color
car1 = Car('red')
car2 = Car('blue')
print(car1.color) # Output: red
print(car2.color) # Output: blue
car1.color = 'green'
print(car1.color) # Output: green
print(car2.color) # Output: blue
In the above example, we defined an instance variable "color" inside the __init__ method of the Car class using the "self" keyword. We then created two instances of the Car class and accessed the "color" variable using the instances. Finally, we changed the value of the "color" variable for the car1 instance only and accessed it again using the instances.
Conclusion
In this tutorial, we learned about class and instance variables in Python 3. Class variables are shared among all instances of a class and can be accessed using the class name or any instance of the class. Instance variables belong to an instance of a class and can only be accessed using an instance of the class.
Keywords: Python, Class Variables, Instance Variables, Object-Oriented Programming, __init__ method, self keyword.
Комментарии
Отправить комментарий