Python Classes and Objects
A class in Python is a user-defined template for creating objects. It bundles data and functions
together, making it easier to manage and use them. When we create a new class, we define a new
type of object. We can then create multiple instances of this object type.
Classes are created using class keyword. Attributes are variables defined inside the class and
represent the properties of the class. Attributes can be accessed using the dot . operator
class teacher:
s = "teaching"
Create Object
An Object is an instance of a Class. It represents a specific implementation of the class and holds its
own data.
class teacher:
s = "teaching"
# Create an object from the class
teacher1 = teacher()
# Access the class attribute
print(teacher1.s)
Creating Object with __init__
class Dog:
species = "Canine" # Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
# Creating an object of the Dog class
dog1 = Dog("Buddy", 3)
print(dog1.name) # Output: Buddy
print(dog1.species) # Output: Canine
output-
Buddy
Canine
Class Variables
These are the variables that are shared across all instances of a class. It is defined at the class level,
outside any methods. All objects of the class share the same value for a class variable unless
explicitly overridden in an object.
Instance Variables
Variables that are unique to each instance (object) of a class. These are defined within __init__
method or other instance methods. Each object maintains its own copy of instance variables,
independent of other objects.
Ex-
class Dog:
# Class variable
species = "Canine"
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Charlie", 5)
# Access class and instance variables
print(dog1.species) # (Class variable)
print(dog1.name) # (Instance variable)
print(dog2.name) # (Instance variable)
# Modify instance variables
dog1.name = "Max"
print(dog1.name) # (Updated instance variable)
# Modify class variable
Dog.species = "Feline"
print(dog1.species) # (Updated class variable)
print(dog2.species)
output-
Canine
Buddy
Charlie
Max
Feline
Feline