Object Oriented Programming Flashcards
Objects as data structures
Object = state + behavior
State and behavior bundled together
Encapsulation - bundling data with code operating on it
classes
Blueprint for objects outlining possible states and behaviors, doesn’t actually contain any data
Objects
Every object has a class Use type() to find the class
State
Attributes - variables
Import numpy as np
A = np.array([1,2,3,4])
#shape attribute A.shape
Behavior
Methods - > functions Import numpy as np A = np.array([1,2,3,4]) #reshape method A.reshape(2,2)
Function of list all attributes and methods
Dir(a)
Add methods to a class
Class customer: Def identify(self,name): Print(“I am Customer” + name)
Use self as the 1st argument in method definition Method definition = function definition within a class Ignore self when calling method on an object
What is self?
Classes are templates, how to refer data of a particular object?
Self is a stand-in for a particular object used in class definition, should be the first argument of any method
Python will take care of self when method called from an object
Cust.identify(“Laura”) will be interpreted as Customer.identify(cust,”Laura”)
Class example
Class Customer: Def set_name(self, new_name): Self.name = new_name #self.name = name creates an attribute called name and assigns to it the value of the name parameter
Def identify(self): Print(“I am Customer” + self.name)
Constructor
\_\_init\_\_() method is called every time an object is created Def \_\_init\_\_(self,name): Self.name = name
Create all attributes in the constructor and not throughout the class definition, attributes are created when the object is created
Instance-level data
Name, salary were instance attributes
Self binds to an instance
Instance is an object that is built from a class and contains real data
Class level data
Data shared among all instances of a class Define a class attribute right after class Use classname.global attribute to call it
Class methods
Methods are already shared; same code for every instance can’t use instance level data
Class MyClass:
@classmethod
Def my_awesome_method(cls,args…)
Use cls instead of self
Can’t use instance attributes
Alternative constructors
@classmethod Def from_file(cls,filename): With open(filename, ‘r’) as f: Name = f.readline() Return cls(name)
What is OOP?
Structuring a program by bundling related properties and behaviors into individual objects
- properties like a name, age, and address
- behaviors such as walking, talking, running
- relations between things
Objects are at the center of the object-oriented programming in Python, not only representing data but also the overall structure of the program