Classes in Python
- Get link
- X
- Other Apps
Class in Python
In Python, a class is a blueprint for creating objects that have similar attributes and methods. It is a fundamental concept in Object-Oriented Programming (OOP) and allows developers to write reusable and modular code.
Defining a Class in Python
To define a class in Python, we use the class
keyword followed by the name of the class. The syntax for defining a class is as follows:
class ClassName: # class attributes and methods
Person
:In this example, the Person
class has two attributes (name
and age
) and one method (greeting
). The __init__
method is a special method in Python that is called when an object of the class is created. It initializes the object's attributes with the values passed to it.
Creating Objects from a Class
To create an object of a class in Python, we use the class name followed by parentheses, like so:
person1 = Person("John", 30)
Person
object called person1
with the name "John" and age 30. We can access the object's attributes using the dot notation, like so:Inheritance in Classes
Inheritance is a key feature of OOP that allows us to create a new class by inheriting the properties of an existing class. The new class is called a subclass or derived class, and the existing class is called the superclass or base class.
To create a subclass in Python, we use the class
keyword followed by the name of the subclass and the name of the superclass in parentheses, like so:
class Student(Person): def __init__(self, name, age, student_id): super().__init__(name, age) self.student_id = student_id def info(self): print(f"My name is {self.name}, I am {self.age} years old, and my student ID is {self.student_id}.")
In this example, the Student
class is a subclass of the Person
class. It has all the attributes and methods of the Person
class, plus an additional attribute student_id
and a new method info
.
We use the super()
function to call the superclass's __init__
method and initialize the object's name
and age
attributes. We can then access these attributes and the student_id
attribute using the dot notation.
Conclusion
In conclusion, a class is a fundamental concept in Python's OOP paradigm. It allows developers to write reusable and modular code by defining objects with attributes and methods. We can create objects from a class using the class name and the dot notation, and we can create subclasses by inheriting the properties of an existing class.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments