Python classes and Objects


Class: A class is a blueprint for defining and creating objects. A class prescribes a set of characteristics known as attributes (these are the class variables) and behaviours known as methods (these are the class functions). Object: An object is an actual instance of a class in a running program. __init__: It is the constructor method in Python. It is automatically called when you create a new object from a class. It is used to initialize the attributes (properties) of the object. self: It refers to the class instance itself. It’s a way to access the object’s attributes and methods. # Class and objects # Class with arguments class Contacts: contact_list = [] def __init__(self, name, contact_number): self.name = name self.contact_number = contact_number def show_contact_number(self): print(f"Contact number of {self.name}: {self.contact_number}") def add_contact(self): self.contact_list.append({"name":self.name, "contact_number": self.contact_number}) def show_contact_list(self): for cnt in self.contact_list: print(cnt) print(f"{cnt.get("name")}: {cnt.get("contact_number")}") contact_object = Contacts("Alice", "9876543210") contact_object.add_contact() contact_object.show_contact_number() contact_object.show_contact_list() # Class without arguments class Mobile: def show_mobile_details(self): print("Brand: Samsung") print("Operating System: Android") print("RAM: 12 GB") print("Processor: Snapdragon") mob = Mobile() mob.show_mobile_details()