Beginning Python OOPs---Start with basic class, constructor and toString
To understand OOPS = Object Oriented Programming start thinking about the wayany machine is made.
A laptop for instance is made of a screen, a hard-disk, a keyboard etc attached to each other.
A car is made in the same manner with a body, wheels, steering wheel and more.
The car parts are then made up of more smaller parts.
We call this a component based design.
Doing the same thing for a software project is OOPS.
Terms in OOPS
1. Class. The blueprint of an object. For example the paper design of a building.
2. Object, The finished object. For example the car or a building.
3. Encapsulation. Aggregation of many objects in another leaving only the interfaces outside.
4. Abstraction. Hiding the processing, concentrating only on the inputs and the output.
"""
Starting OOPs in Python.
The topics we will cover are.
1. Making Classes
2. Methods inside classes
3. Using classes inside classes
4. Inheritance
5. Multiple inheritance
6. Operator overloading
"""
class Book: # Definiton of class begins
def __init__(self, bookName, price, subject): # Constructor
# self is the equivalent of this in Java and CPP. We can use any name for self.
# def __init__(xyz, bookName, price, subject): is also valid
self.bookName = bookName # Copy bookName parameter to the class variable
self.price = price
self.subject = subject
def __str__(self): # toString. WIll be used if class object is printed
return "Bookname = {0}, Price = {1}, Subject = {2}".format(self.bookName, self.price, self.subject)
b1 = Book("Basic C", 100, "Cb")
b2 = Book("Adv C", 100, "C")
print(b1)
print(b2)
print("Book = {0}".format(b1))
Git Repo
Output
C:\Users\Lenovo\AppData\Local\Microsoft\WindowsApps\python3.10.exe C:/pythoncodecamp/OOPs/book.py
Bookname = Basic C, Price = 100, Subject = Cb
Bookname = Adv C, Price = 100, Subject = C
Book = Bookname = Basic C, Price = 100, Subject = Cb
Process finished with exit code 0
Next, we use the above class in another class
import book as book
'''
Using a class in another class. We have imported the Book class
'''
class Person:
def __init__(self, name, age, address, mybook):
self.name = name
self.address = address
self.age = age
self.book = mybook
def __str__(self):
return "Name={0}, Age = {1}, Address={2}, Book=({3})".format(self.name, self.age, self.address, self.book)
b1 = book.Book("Basic C", 100, "C")
p = Person("Raju", 50, "Delhi", b1)
print(p)
Git Repo
Output
C:\Users\Lenovo\AppData\Local\Microsoft\WindowsApps\python3.10.exe C:/pythoncodecamp/OOPs/Person.py
Bookname = Basic C, Price = 100, Subject = Cb
Bookname = Adv C, Price = 100, Subject = C
Book = Bookname = Basic C, Price = 100, Subject = Cb
Name=Raju, Age = 50, Address=Delhi, Book=(Bookname = Basic C, Price = 100, Subject = C)
Process finished with exit code 0
0 Comments