Classes and Objects in Python
Object-Oriented Programming (OOP) in Python starts with the concepts of classes and objects.
What is a Class?
A class is a blueprint or a template for creating objects. It defines a set of attributes that will characterize any object that is instantiated from this class.
What is an Object?
An object is an instance of a class. It is a realized version of the class, containing actual data.
Instance vs. Class Variables
- Class Variables: Shared among all instances of a class. They are defined inside the class but outside any methods.
- Instance Variables: Unique to each instance. They are defined inside methods, typically the
__init__method.
The __init__ Method
the init method is one which contains variables which should be passed when a new object of that class is created.
eg.
class User:
def __init__(self, userid, surname=None):
self.userid = userid
self.surname = surname
user = User(userid)
- Required Parameters - Here we create a user object of User Type. Users must always have a userid to even be started so we have to put it inside init.
- Optional Parameters -lets say some users have surname and some dont, so we just initialize the variable in init, but we mark it as default value of None, so that if in case user doesnt provide it, the value falls back to default value and it is None. Lets initialize the 2 user objects, one having optional surname and one without it.
user = User("user1", "Verma")
user2 = User("user2")
Final Example of a Class Implementation
class Dog:
# Class variable
species = "Canis familiaris"
def __init__(self, name, age, color=None):
# Instance variables
self.name = name
self.age = age
self.color = color
def description(self):
if self.color:
return f"{self.name} is {self.age} years old and is {self.color}."
else
return f"{self.name} is {self.age} years old."
# Creating objects
buddy = Dog("Buddy", 9)
miles = Dog("Miles", 4, 'brown')
print(miles.description()) # Output: Miles is 4 years old and is brown.
print(buddy.species) # Output: Canis familiaris