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
__init__()
__init__() sets the initial state of the object by assigning the values of the object’s properties - initialized each new instance of the class
First parameter will always be a variable called self Instance is automatically passed to the self parameter when a new class instance is created So new attributes can be defined on the object
__str__()
If you want to print something, use __str__(self)
Def \_\_str\_\_(self): Return f”{self.name} is {self.age} years old”
Class inheritance
Use old code and add new functionality to the old to create new class
Class MyChild(MyParent):
MyParent: class whose functionality is being extended/inherited MyChild: class that will inherit the functionality and add more
Child class has all the parent data, don’t have to define in the new class if it is already in the parent data
Add new functionality to child class
Class SavingsAccount(BankAccount): def \_\_init\_\_(self, balance, interest_rate): BankAccount.\_\_init\_\_(self,balance) # self is a SavingsAccount but also a BankAccount
Add more functionality by defining new methods
Use data from both parent and child class
Can change the signature(add parameters)
Use Parent.method(self,args…) to call a method from the parent class
Operator overloading
__eq__() called when 2 objects of a class are compared using ==
Custom comparison code (self and other) return a boolean value, true or false
There are not eq, greater or equal, less than, etc
__hash__ - use objects as dictionary keys and in sets
Str and repr classes
__repr__() - repr(obj), printing in consol, formal, for developer, reproducible representation, fallback for print
__str__() - print(obj), str(obj) - informal for end user, string representation
Except order
List except blocks in the increasing order of specificity - children before parents so that the children exception will be called in the parent except block
Polymorphism
Using a unified interface to operate on objects of different classes
For example, a method to withdraw from a batch of different accounts, if the accounts fall in different classes but all have the method withdraw, python can withdraw from any object that has a withdraw method
Liston substitution principle
no LSP no inheritence
Base class should be interchangeable with any of its subclasses without altering any properties of the programs
Syntactically - function signatures are compatible - arguments and returned values semantically - state of the object and the program remains consistent (subclass method doesnt’ strengthen input or weaken output conditions, no additional exceptions)
Restricting access
Class data is public
Naming convention: internal
Obj._att_name, obj._method_name()
- starts with a single _ => “internal”
- not a part of the public API
- internal details of implementation
- as a class user: “don’t touch this”
- i.e a helper method that checks validity of an attribute’s value but isnt’ considered part of class’s public interface
Naming convention: pseudo private
Obj.__atrr_name, obj.__method_name()
- starts but doesn’t end with __ —> “private”
- not inherited
- name mangling: obj.__atr_name is interpreted as obj._MyClass__attr_name
- double leading underscores are used for attributes that should not be inherited to avoid name clashes in child classes
- a “version” attribute that stores the current version of the class and shouldn’t be passed to child classes, who will have their own versions
Control attribute access
Make attributes read only
Restricted and read-only
For data frames, you can’t just change the number of columns or the shape of it if it doesn’t adhere to the dataframe structure
How to control attribute access
Use “protected” attribute with leading _ to store data
1) define constructor (__init__)
2) use @property on a method whose name is exactly of the restricted attribute; return the internal attribute
Def salary(self):
Return self._salary
3) to define how an attribute is set, use @attr.setter on a method attr() that will be called on obj.attr = value
Method with the property decorator returns the data and the method with salary dot setter decorator implements validation and sets the attribute
Add @attr.getter
Use for the method that is called when the property’s value is retrieved