Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

This is object oriented programming cheatsheet

License

NotificationsYou must be signed in to change notification settings

niloycste/Object-Oriented-Programming-Cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Core Concept of OOP

Lets talk about what isOOP in a layman language.

Imagine you're building a virtual world, like a video game or a simulation. In this world, everything can be thought of as objects. Objects are like characters or things that have characteristics (attributes) and can do things (methods).

Class: Class is a blueprint like how an object will behave.Objects: These are the main entities in your virtual world. For example, if you're creating a game, an object could be a player, an enemy, or a weapon.Objects are mutable like list,dict and sets cause it works like value by reference like it stores the data in a same location.

Attributes: These are the characteristics or properties of the objects. For a player object, attributes might include the player's name, health, and score.

Methods: These are the actions or behaviors that objects can perform. In a game, a player object might have methods like "move," "attack," or "collect items."

Encapsulation: This is like putting things in a box. It means that an object keeps its attributes and methods together, and the outside world doesn't need to know all the details. For example, when you play a game, you don't need to know how the player's health is calculated; you just see the current health value.

Inheritance: This is like passing down traits in a family. One object can inherit attributes and methods from another object. For instance, if you have a general "character" object, a "player" object could inherit from it and add specific player-related features.

Polymorphism: This is like using the same word in different contexts. It allows different objects to be treated as instances of the same type. For example, both a player and an enemy might have a "damage" method, but they would behave differently.

Break Down Each of the concepts with code and example

Function vs Method:

Functions

  • Definition: A function is a standalone block of code that performs a specific task. It is defined outside of any class or object.

  • Usage: Functions can be called from anywhere in the code, as long as they are in the same scope or imported.

  • Example:

    defadd_numbers(a,b):returna+bresult=add_numbers(5,7)

Methods

  • Definition: A method is a function associated with an object. It is defined within a class and is called on instances of that class.

  • Usage: Methods are called on objects and operate on the data within those objects.

  • Example:

    classCalculator:defadd_numbers(self,a,b):returna+bcalc=Calculator()result=calc.add_numbers(5,7)
  • Short Note: lets we have a list l and we want to find out length of this list.so we will write len(l) , but if we append something in a list we will write l.append(). cause len is a function and append, copy, pop,remove etc are a method of a list class.

Constructor

A constructor is like a setup wizard for objects in programming. It's a special method, often named__init__, that runs automatically when create an object. Its main job is to initialize the object's attributes or perform any necessary setup.In Python:

classMyClassdef__init__(self,initial_pin,initial_balance):# this is constructorself.pin=initial_pin# instance variable#  we call it instance variable cause we write it within the constructor and value will be different for each objectself.balance=initial_balance# instance variablemy_object=MyClass("1234",1000)
  • Short Note:

  • we usually write any sort of configuration related task in the constructor like database connectivity, hardware connectivity etc.so basically we dont want to give specific control to the user and that time we will use constructor.

  • Inside Class only two things are possible one is data and other one is method. Only object of this class can access that data and method even one method can't access another method and its datas within the class. if one method is trying to access another method we need and object and asself is the current object so we can access if we use self and thats why we useself.

Simple Implementation based onclass,constructor,method andobject

Now let's write a code to understand oop better based on atm system

classAtm:def__init__(self) :# Constructorself.pin=""self.balance=0self.menu()#we can access menu method property cause we use selfdefmenu(self):# methoduser_input=input("""                        Hello, How would you like to proceed                         1.Enter 1 to create pin                         2.Enter 2 to deposit                         3.Enter 3 to Withdraw                         4.Enter 4 to check balance                         5.Enter 5 to exit                        """)ifuser_input=="1":self.create_pin()elifuser_input=="2":self.deposit()elifuser_input=="3":self.withdraw()elifuser_input=="4":self.check_balance()else:print("Bye")# methodsdefcreate_pin(self):self.pin=input("Enter your pin : ")print("Pin set sucessfully")defdeposit(self):temp=input("Enter your pin : ")iftemp==self.pin:amount=int(input("Enter the amount : "))self.balance=self.balance+amountprint("Deposit Sucessfully")else:print("Invalid pin")defwithdraw(self):temp=input("Enter your pin : ")iftemp==self.pin:amount=int(input("Enter the amount : "))ifamount<self.balance:self.balance=self.balance-amountprint("operation sucessfull")else:print("Insufficient Funds")else:print("Invalid Pin : ")defcheck_balance(self):temp=input("Enter your pin : ")iftemp==self.pin:print(self.balance)else:print("invalid pin")# Object creation name bank based on the class Atmbank=Atm()

Encapsulation

Usually object can access everything like datas and methods so anyone can change the data so good practise is to hide the data.In pyhton we use__ to hide the data and method. but fun fact is in python nothing is truely private. anyone can access the private data using class name and that data_name. lets give an example. lets we have a class nameAtm and private data name__balance and object namevalue. now we can access that private data usingvalue._Atm__balance. whatever in conventional method we usegetter andsetter emthod to access the data.Let's implement the encapsulation concept on our previous code.

# We will build a real life project to understand oop better based on the atm transaction#classAtm:def__init__(self) :self.__pin=""# hide the data using `__` so that user can't see that dataself.__balance=0self.__menu()# we use getter and setter method to access the private datadefget_pin(self):returnself.__pindefset_pin(self,new_pin):iftype(new_pin)==str:self.__pin=new_pinprint("print changed")else:print("not allowed")def__menu(self):# we can also hide the method alsouser_input=input("""                        Hello, How would you like to proceed                         1.Enter 1 to create pin                         2.Enter 2 to deposit                         3.Enter 3 to Withdraw                         4.Enter 4 to check balance                         5.Enter 5 to exit                        """)ifuser_input=="1":self.create_pin()elifuser_input=="2":self.deposit()elifuser_input=="3":self.withdraw()elifuser_input=="4":self.check_balance()else:print("Bye")defcreate_pin(self):self.__pin=input("Enter your pin : ")print("Pin set sucessfully")defdeposit(self):temp=input("Enter your pin : ")iftemp==self.__pin:amount=int(input("Enter the amount : "))self.__balance=self.__balance+amountprint("Deposit Sucessfully")else:print("Invalid pin")defwithdraw(self):temp=input("Enter your pin : ")iftemp==self.__pin:amount=int(input("Enter the amount : "))ifamount<self.__balance:self.__balance=self.__balance-amountprint("operation sucessfull")else:print("Insufficient Funds")else:print("Invalid Pin : ")defcheck_balance(self):temp=input("Enter your pin : ")iftemp==self.__pin:print(self.__balance)else:print("invalid pin")

This is the class diagram :

Collection of Objects

we can keep the objects as a list, dict

classCustomer:def__init__(self,name,age):self.name=nameself.age=agec1=Customer("niloy",26)c2=Customer("nayan",27)c3=Customer("piyas",30)L=[c1,c2,c3]# pass the objects in a listforiinL:print(i.name,i.age)

Variables

Instance Variable:we write instance variable within the constructor and value will be different for each objects.Static/Class Variable:The value of a variable will be same for each objects. like if we want to storeIFSC code and asIFSC code same for a branch so take it as a static variable.

classAtm:__counter=1# Static/Class varibledef__init__(self) :self.__pin=""#instance variableself.__balance=0# instance variableself.serialno=Atm.__counter# to access static variable we write class name.static variable like Atm.counterAtm.__counter=Atm.__counter+1@staticmethoddefget_counter():returnAtm.__counter#for static variable we dont need to use `self`. as we use this getter and setter method access the static variable so we dont need to use selfdefset_counter(new):iftype(new)==int:Atm.__counter=newelse:print("Not Allowed")defget_pin(self):returnself.__pindefset_pin(self,new_pin):iftype(new_pin)==str:self.__pin=new_pinprint("print changed")else:print("not allowed")

Relationship

Aggregation:It is also calledHas-A relationship. Like if we have two class name customer and address and customer is trying to access address so this isHas-A relationship.we usediamond sign to indicate aggregation in class diagram.

classCustomer:def__init__(self,name,gender,address):self.name=nameself.gender=genderself.address=addressdefedit_profile(self,new_name,new_city,new_pin,new_state):self.name=new_nameself.address.change_address(new_city,new_pin,new_state)#aggregationclassAddress:def__init__(self,city,pincode,state):self.city=cityself.pincode=pincodeself.state=statedefchange_address(self,new_city,new_pin,new_state):self.city=new_cityself.pincode=new_pinself.state=new_stateadd=Address("Comilla",3519,"Chittagong")cust=Customer("Niloy","Male",add)#when we give address of a customer we pass Address class object `add`cust.edit_profile("Nayan","Dhaka",3510,"manik")print(cust.address.city)

Inheritance:It is also calledIs-A relationship.Inheritance is a fundamental concept in object-oriented programming, allowing a new class to inherit the properties and behaviors of an existing class.In inheritance child class can inherit parent class property but parent class can't inherit child class property.we usually inheritdatamembers,method andconstructor but we are not allowed to inheritprivate datamember.

Short Note:If we have two class and if parent class has constructor and child class one doesn't have any constructor but we create an object of child class that time parent class constructor will be called.

# Base class UserclassUser:def__init__(self,username,email):self.username=usernameself.email=emaildeflogin(self):print(f"{self.username} is logging in")defregister(self):print(f"{self.username} is registering")# Base class StudentclassStudent:def__init__(self,student_id,courses):self.student_id=student_idself.courses=coursesdefenroll(self):print(f"Student{self.student_id} is enrolling in courses")defreview(self):print(f"Student{self.student_id} is reviewing courses")# Derived class StudentUser inheriting from both User and StudentclassStudentUser(User,Student):def__init__(self,username,email,student_id,courses):# Calling the constructors of both base classesUser.__init__(self,username,email)Student.__init__(self,student_id,courses)# Creating an instance of the derived classstudent_user=StudentUser("niloy islam","niloy@gmail.com","S12345", ["Math","Physics"])# Accessing methods from both base classesstudent_user.login()student_user.enroll()
  • Types of Inheritance:

Multiple Inheritance:

classA:defmethod_A(self):print("Method A")classB:defmethod_B(self):print("Method B")classC(A,B):defmethod_C(self):print("Method C")# Example usagec_instance=C()c_instance.method_A()# Accessing method from class Ac_instance.method_B()# Accessing method from class Bc_instance.method_C()# Accessing method from class C

Hierarchical Inheritance:

classShape:defdraw(self):print("Drawing a shape")classCircle(Shape):defdraw(self):print("Drawing a circle")classSquare(Shape):defdraw(self):print("Drawing a square")# Example usagecircle_instance=Circle()circle_instance.draw()# Accessing overridden method in Circle classsquare_instance=Square()square_instance.draw()# Accessing overridden method in Square class

Multilavel Inheritance:

classAnimal:defspeak(self):print("Animal speaks")classDog(Animal):defbark(self):print("Dog barks")classGermanShepherd(Dog):defguard(self):print("German Shepherd guards")# Example usagegerman_shepherd_instance=GermanShepherd()german_shepherd_instance.speak()# Accessing method from Animal classgerman_shepherd_instance.bark()# Accessing method from Dog classgerman_shepherd_instance.guard()# Accessing method from GermanShepherd class

Polymorphism

Polymorphism is the ability of a class to take on multiple forms, where an object can represent different types or have different behaviors based on the context. There are two types of polymorphism

  • Method Overloading:Method overloading is the ability to define multiple methods in the same class with the same name but with a different number or type of parameters.It is also called compile time polymorphism
classCalculator:defadd(self,a,b):returna+bdefadd(self,a,b,c):returna+b+ccalc=Calculator()print(calc.add(1,2))# Raises an error as there is no add method with two parametersprint(calc.add(1,2,3))# Outputs: 6

method overloading is attempted in the Calculator class, but it's not directly supported in Python like in some other languages. In Python, when we define multiple methods with the same name in a class, the last one defined will override the previous ones.

  • Method Overridning:Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.It is alsocalled runtime polymorphism or dynamic polymorphism.
classPhone:def__init__(self,price,brand,camera):print("Inside the constructor")self.price=priceself.brand=brandself.camera=cameradefbuy(self):print("Buying a phone")classSmartPhone(Phone):defbuy(self):print("Buying smartphone")s=SmartPhone(17200,"REDMI Note 10S",64)# Phone class constructor will be called as SmartPhone doesn't have constructorprint(s.price,s.brand,s.camera)s.buy()# SmartPhone method buy will be called not Phone class method cause we create an object of SmartPhone.

Super() keyword

usingsuper() we can invoke parent class method and constructor.

classPhone:def__init__(self,price,brand,camera):print("Inside the constructor")self.price=priceself.brand=brandself.camera=cameradefbuy(self):print("Buying a phone")classSmartPhone(Phone):defbuy(self):print("Buying smartphone")super().buy()#using super we can invoke parent class method and constructor sp parent class buy() method will be calleds=SmartPhone(17200,"REDMI Note 10S",64)# Phone class constructor will be called as SmartPhone doesn't have constructorprint(s.price,s.brand,s.camera)s.buy()# SmartPhone method buy will be called not Phone class method cause we create an object of SmartPhone.

Let's take another example where we use constructor in the both classes.

classPhone:def__init__(self,price,brand,camera):print("Inside the phone constructor")self.price=priceself.brand=brandself.camera=cameraclassSmartPhone(Phone):def__init__(self,price,brand,camera,os,ram):print("this portion will execute first")super().__init__(price,brand,camera)self.os=osself.ram=ramprint("inside smartphone constructor")s=SmartPhone(17200,"REDMI Note 10S",64,"Android",6)print(s.os,s.brand)

Abstraction

abstraction refers to the concept of hiding the complex implementation details of an object and exposing only the essential features and functionalities to the outside world. It involves creating abstract classes and interfaces that define the common properties and behaviors that a group of related objects should have, without specifying the details of how those properties and behaviors are implemented.
The actual use case is parent class make sure that child classes should obey parent class instruction like makeabstract method's method in their class and write some code in that method's body.

Abstract Class:Abstract Classes: An abstract class is a class that cannot be instantiated on its own and may contain abstract methods (methods without a body). Abstract classes serve as blueprints for other classes and define a common interface for a group of related classes. In Python, we can create an abstract class using the ABC (Abstract Base Class) module. we can't create the abstract class object.

fromabcimportABC,abstractmethodclassBankApp(ABC):defdatabase(self):print("connected to database")@abstractmethoddefsecurity(self):passclassMobileApp(BankApp):defmobile_login(self):print("login into mobile")defsecurity(self):print("mobile security")# we must make security method in this class which is abstract method of its parent class `BankApp`, otherwise we can't inherit.mob=MobileApp()mob.security()mob.mobile_login()

Notes:

This is open source. If you are interested, you can contribute to this documentation. Just fork this repository and make the changes or add new content.

About

This is object oriented programming cheatsheet

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp