Object-oriented programming (OOP) organises code around objects that hold data and actions. Python classes are the way you build those objects, and most frameworks and interview questions rely on them.
A class and an object
A class is a blueprint, such as a Student. An object is one instance of that blueprint, such as a particular student named Asha. Each object has its own data.
Methods and attributes
- Attributes: the data stored in the object, such as name and marks.
- Methods: the functions that belong to the object, such as calculate_average().
- __init__: the method that runs when you create a new object, and sets its starting data.
Inheritance
A child class can reuse the attributes and methods of a parent class, and add or change some. Use inheritance when two things share most of their behaviour, not just a few lines of code.
A practice exercise
Write a BankAccount class with a balance, a deposit method and a withdraw method that refuses to go below zero. Then create two accounts and test each one.
Next step: see our Python Full Stack course at ScholarLogic, or book a free demo class. A counsellor will share the fee and the next batch dates.
