Day 02: Getting Started with OOP in Python – Classes & Objects


Today I began my journey into Object Oriented Programming (OOP) in Python. OOP is a programming paradigm based on the concept of "objects", which can contain data and code — data in the form of attributes, and code in the form of methods.
1. Class
A class is like a blueprint for creating objects.
class Student:
pass
2. Object
An object is an instance of a class.
c1 = Student()
print(type(c1))
3. Constructor (__init__
)
This special method is called when an object is created.
class Student():
def __init__(self,name,marks):
self.name = name
self.marks = marks
s1 = Student("Mr stark",89)
print(s1.name)
4. Instance Variables & Methods
class Hello():
def __init__(self,name):
self.name = name
def greet(self):
print(f"Hello, I’m {self.name}!")
h1 = Hello("Ironman")
print(h1.greet())
5. Class & Instance Attribute
class Students:
college_name = "ABC"
name = "Anonymous"
def __init__(self,name,marks):
self.name = name
self.marks = marks
print("Adding new sutdent in Database")
s1 = Students("Karan", 97)
print(s1.name)
print(s1.college_name)
In the above code snippet college_name
is a class Attribute that is defined for all the objects that we are creating and is valid for all like we are doing s1.college_name
which gives us “ABC
”
Subscribe to my newsletter
Read articles from Shiva directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Shiva
Shiva
A self taught data scientist