Classes in Python
In Python, classes are used to create new types of objects with specific properties and behaviors. They serve as blueprints for creating objects, allowing you to encapsulate data and functionality into a single unit. Here's an overview of classes in Python:
Defining a Class: You define a class using the
class
keyword followed by the class name. The class definition typically contains class variables, methods, and possibly a constructor (__init__
method).pythonCopy codeclass MyClass: # Class variable class_variable = 123 # Constructor (initializer) def __init__(self, arg1, arg2): self.arg1 = arg1 self.arg2 = arg2 # Instance method def instance_method(self): print("This is an instance method") @classmethod def class_method(cls): print("This is a class method")
Creating Objects (Instances): Once a class is defined, you can create objects (instances) of that class using the class name followed by parentheses.
pythonCopy codeobj1 = MyClass(10, 20) obj2 = MyClass(30, 40)
Instance Variables: Instance variables are unique to each instance of a class. They are defined within methods using the
self
keyword.Class Variables: Class variables are shared among all instances of a class. They are defined outside of any method within the class.
Methods: Methods are functions defined within a class. They can be instance methods, class methods, or static methods.
Instance Methods: They operate on instance variables and are called on objects.
Class Methods: They operate on class variables and are called on the class itself using
@classmethod
decorator.Static Methods: They don't operate on instance or class variables and are defined using
@staticmethod
decorator.
Constructor (
__init__
Method): The__init__
method is a special method called when an object is created. It is used to initialize instance variables.Instance Attributes: You can add new attributes to instances dynamically.
pythonCopy codeobj1.new_attribute = "New value"
Inheritance: Classes can inherit attributes and methods from other classes. This promotes code reusability and allows for creating a hierarchy of classes.
pythonCopy codeclass SubClass(MyClass): pass
Encapsulation: Classes in Python support encapsulation, which means the internal representation of an object is hidden from the outside world. You can control access to attributes and methods using access modifiers such as public, protected, and private.
Destructors (
__del__
Method): The__del__
method is called when an object is about to be destroyed. It is used to perform cleanup tasks.
Classes are fundamental to object-oriented programming (OOP) in Python, enabling you to create organized and reusable code structures. They are widely used in various Python libraries and frameworks. Check out the online tutorial for more insights.