Python OOP Practice Code Notes
# Class: Student with Parameterized Constructor
class student:
college_name = "timepass"
name = "ram"
def __init__(self, name, marks):
print("hello student")
self.name = name
self.marks = marks
s1 = student("gaurav", 97)
print(s1.name)
print(s1.marks)
s2 = student("aryan", 99)
print(s2.name)
print(s2.marks, s2.college_name, student.college_name)
# Class: Car
class car:
def __init__(self, color, brand, drive):
print("about car")
self.color = color
self.brand = brand
self.drive = drive
car1 = car("yellow", "rollsroyce", "auto")
print(car1.color)
print(car1.brand, car1.drive)
car2 = car("red", "mghector", "manual")
print(car2.color, car2.brand, car2.drive)
# Class: Students with Average Calculation
class Students:
def __init__(self, name, maths, phy, chem):
self.name = name
self.maths = maths
self.phy = phy
self.chem = chem
self.subject = [maths, phy, chem]
def get_avg(self):
total = 0
count = 0
for value in self.subject:
total = total + value
count = count + 1
return total / count
s1 = Students("harris", 86, 78, 76)
print("hi", s1.name, ", avg score:", s1.get_avg())
# Class: Account with Encapsulation (Private Attribute)
class Account:
def __init__(self, acc_no, acc_pass):
self.account_no = acc_no
self.__account_pass = acc_pass
def get_pass(self):
print(self.__account_pass)
cust1 = Account(123456, "zxcvbnm")
print(cust1.account_no)
cust1.get_pass()
# Class: Person with Private Method
class Person:
__name = "anonymous"
def __hello(self):
print("hi, user")
def welcome(self):
self.__hello()
p1 = Person()
p1.welcome()