In Python, Classes are a fundamental part of object-oriented programming (OOP).
Classes are user-defined data-types that contain both the properties and the methods and are used to fetch and manipulate data.
Classes can be considered to be templates for creating objects. an object can contain all the characteristics and operations a class has.
They serve as blueprints for creating objects (instances) that possess attributes (variables) and behaviours (methods).
Here's a basic overview of classes in Python:
To define a class in Python, we use the class keyword followed by the class name.
Inside the class block, we can define attributes and methods.
class YourClass: # Class attribute class_attribute = "I am a class attribute" # Constructor method (initializer) # This is the constructor method it will invoked when creating a new MyClass object # It takes two parameters, arg1 and arg2, and initializes them as attributes of the object def __init__(self, arg1, arg2): # Instance attributes self.arg1 = arg1 self.arg2 = arg2 # Instance method def instance_method(self): return "This is an instance method"
The self-parameter indicates the current instance of the class and accesses the class variables. We can give any name to `self`, but it needs to be the first parameter of any function that belongs to the class.
class YourClass: def __init__(self, arg1, arg2): # Instance attributes self.arg1 = arg1 self.arg2 = arg2
__init__ method: is the constructor method it will invoke when creating a new Class object and is used to set the object properties. It takes the first argument `self` which indicates the current instance of a class. we can also set more parameters to an object while creating a new object, for that, we need to declare more parameters into function.
__init__ is the constructor method it will invoke when creating a new YourClass object
It takes two parameters, arg1 and arg2, and initializes them as attributes of the object
# Creating objects of YourClass obj1 = YourClass("argument1", "argument2") obj2 = YourClass("first argument", "second argument")
Once a class is defined, we can create objects (instances) of that class using the class name followed by parentheses.
We can access attributes and methods of an object using dot `.` notation.
# Creating objects of YourClass obj1 = YourClass("argument1", "argument2") obj2 = YourClass("first argument", "second argument") # Accessing `obj1` instance attributes print(obj1.arg1) # Output: argument1 print(obj1.arg2) # Output: argument2 # Accessing `obj2` instance attributes print(obj2.arg1) # Output: first argument print(obj2.arg2) # Output: Second argument # Accessing class attribute print(YourClass.class_attribute) # Output: I am a class attribute # Calling instance method print(obj1.instance_method()) # Output: I'm instance method