Python OOP: Classes and Objects
A class is a blueprint; __init__ is the constructor, and self refers to the current object.
class Student:
college = "ABC Institute" # class attribute
def __init__(self, name, marks):
self.name = name # instance attributes
self.marks = marks
def result(self):
return "Pass" if self.marks >= 40 else "Fail"
s = Student("Neha", 67)
print(s.name, s.college, s.result())
Neha ABC Institute Pass
Inheritance and Overriding
class Shape:
def area(self):
return 0
class Rect(Shape):
def __init__(self, l, b):
self.l, self.b = l, b
def area(self):
return self.l * self.b
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return round(3.14159 * self.r ** 2, 2)
for sh in [Rect(4, 5), Circle(2)]:
print(type(sh).__name__, sh.area()) # polymorphism
Rect 20
Circle 12.57
Encapsulation
Prefix an attribute with __ to make it "private" (name-mangled). Prefix with _ to signal "internal use".
class Account:
def __init__(self):
self.__balance = 0
def deposit(self, amt):
if amt > 0:
self.__balance += amt
@property
def balance(self):
return self.__balance
a = Account(); a.deposit(500)
print(a.balance)
500
Track your progress through the Python course