Classes and objects in Python
Introduction to classes and objects
Classes and objects are fundamental concepts in object-oriented programming (OOP). A class is a blueprint or template for creating objects, while an object is an instance of a class.
Defining a class in Python
In Python, a class is defined using the class
keyword, followed by the name of the class and a colon. The class body contains attributes and methods:
class MyClass:
# class attributes
attr1 = "Hello"
attr2 = "World"
# class method
def my_method(self):
print(self.attr1 + " " + self.attr2)
Creating objects from a class
To create an object from a class, you simply call the class as if it were a function:
my_object = MyClass()
Class attributes and instance attributes
A class attribute is a variable that is shared by all instances of the class. An instance attribute is a variable that is unique to each instance of the class. You can access and modify class and instance attributes using dot notation:
class MyClass:
class_attr = "I am a class attribute"
def __init__(self, instance_attr):
self.instance_attr = instance_attr
my_object = MyClass("I am an instance attribute")
print(MyClass.class_attr)
print(my_object.instance_attr)
Methods in a class
A method is a function that is associated with a class. Methods can access and modify class and instance attributes:
class MyClass:
class_attr = "I am a class attribute"
def __init__(self, instance_attr):
self.instance_attr = instance_attr
def my_method(self):
print(self.class_attr)
print(self.instance_attr)
my_object = MyClass("I am an instance attribute")
my_object.my_method()
Conclusion
Classes and objects are powerful concepts that enable you to write reusable, modular, and scalable code. By mastering these concepts in Python, you can create complex applications and systems with ease.