What is OOP?
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Alex Yarosh
Content Quality Analyst @ DataCamp
Procedural programming
Code as a sequence of steps
Great for data analysis
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Thinking in sequences
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Procedural programming Object-oriented programming
Code as a sequence of steps Code as interactions of objects
Great for data analysis and scripts Great for building frameworks and tools
Maintainable and reusable code!
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Objects as data structures
Object = state + behavior
Encapsulation - bundling data with code operating on it
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Classes as blueprints
Class : blueprint for objects outlining possible states and behaviors
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Classes as blueprints
Class : blueprint for objects outlining possible states and behaviors
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Objects in Python
Everything in Python is an object Object Class
Every object has a class
5 int
Use type() to nd the class
"Hello" str
import numpy as np
pd.DataFrame() DataFrame
a = np.array([1,2,3,4])
print(type(a)) np.mean function
... ...
numpy.ndarray
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Attributes and methods
State ↔ attributes Behavior ↔ methods
import numpy as np import numpy as np
a = np.array([1,2,3,4]) a = np.array([1,2,3,4])
# shape attribute # reshape method
a.shape a.reshape(2,2)
(4,) array([[1, 2],
[3, 4]])
Use obj. to access attributes and
methods
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Object = attributes + methods
attribute ↔ variables ↔ obj.my_attribute ,
method ↔ function() ↔ obj.my_method() .
import numpy as np
a = np.array([1,2,3,4])
dir(a) # <--- list all attributes and methods
['T',
'__abs__',
...
'trace',
'transpose',
'var',
'view']
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Let's review!
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Class anatomy:
attributes and
methods
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Alex Yarosh
Content Quality Analyst @ DataCamp
A basic class
class <name>: starts a class de nition
class Customer:
# code for class goes here code inside class is indented
pass use pass to create an "empty" class
c1 = Customer()
use ClassName() to create an object of class
c2 = Customer() ClassName
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Add methods to a class
class Customer: method de nition = function de nition within
class
def identify(self, name):
use self as the 1st argument in method
print("I am Customer " + name)
de nition
cust = Customer() ignore self when calling method on an
cust.identify("Laura") object
I am Customer Laura
OBJECT-ORIENTED PROGRAMMING IN PYTHON
class Customer:
def identify(self, name):
print("I am Customer " + name)
cust = Customer()
cust.identify("Laura")
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 de nition
should be the rst 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")
OBJECT-ORIENTED PROGRAMMING IN PYTHON
We need attributes
Encapsulation: bundling data with methods that operate on data
E.g. Customer 's' name should be an attribute
Attributes are created by assignment (=) in methods
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Add an attribute to class
class Customer:
# set the name attribute of an object to new_name
def set_name(self, new_name):
# Create an attribute by assigning a value
self.name = new_name # <-- will create .name when set_name is called
cust = Customer() # <--.name doesn't exist here yet
cust.set_name("Lara de Silva") # <--.name is created and set to "Lara de Silva"
print(cust.name) # <--.name can be used
Lara de Silva
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Old version New version
class Customer: class Customer:
def set_name(self, new_name):
self.name = new_name
# Using a parameter # Using .name from the object it*self*
def identify(self, name): def identify(self):
print("I am Customer" + name) print("I am Customer" + self.name)
cust = Customer() cust = Customer()
cust.set_name("Rashid Volkov")
cust.identify("Eris Odoro") cust.identify()
I am Customer Eris Odoro I am Customer Rashid Volkov
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Let's practice!
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Class anatomy: the
__init__ constructor
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Alex Yarosh
Content Quality Analyst @ DataCamp
Methods and attributes
Methods are function de nitions within a class class MyClass:
# function definition in class
self as the rst argument
# first argument is self
De ne attributes by assignment def my_method1(self, other_args...):
# do things here
Refer to attributes in class via self.___
def my_method2(self, my_attr):
# attribute created by assignment
self.my_attr = my_attr
...
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Constructor
Add data to object when creating it?
Constructor __init__() method is called every time an object is created.
class Customer:
def __init__(self, name):
self.name = name # <--- Create the .name attribute and set it to name parameter
print("The __init__ method was called")
cust = Customer("Lara de Silva") #<--- __init__ is implicitly called
print(cust.name)
The __init__ method was called
Lara de Silva
OBJECT-ORIENTED PROGRAMMING IN PYTHON
class Customer:
def __init__(self, name, balance): # <-- balance parameter added
self.name = name
self.balance = balance # <-- balance attribute added
print("The __init__ method was called")
cust = Customer("Lara de Silva", 1000) # <-- __init__ is called
print(cust.name)
print(cust.balance)
The __init__ method was called
Lara de Silva
1000
OBJECT-ORIENTED PROGRAMMING IN PYTHON
class Customer:
def __init__(self, name, balance=0): #<--set default value for balance
self.name = name
self.balance = balance
print("The __init__ method was called")
cust = Customer("Lara de Silva") # <-- don't specify balance explicitly
print(cust.name)
print(cust.balance) # <-- attribute is created anyway
The __init__ method was called
Lara de Silva
0
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Attributes in methods Attributes in the constructor
class MyClass: class MyClass:
def my_method1(self, attr1): def __init__(self, attr1, attr2):
self.attr1 = attr1 self.attr1 = attr1
... self.attr2 = attr2
...
def my_method2(self, attr2): # All attributes are created
self.attr2 = attr2 obj = MyClass(val1, val2)
...
easier to know all the attributes
obj = MyClass() attributes are created when the object is
obj.my_method1(val1) # <-- attr1 created
created
obj.my_method2(val2) # <-- attr2 created
more usable and maintainable code
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Best practices
1. Initialize attributes in __init__()
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Best practices
1. Initialize attributes in __init__()
2. Naming
CamelCase for classes, lower_snake_case for functions and attributes
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Best practices
1. Initialize attributes in __init__()
2. Naming
CamelCase for class, lower_snake_case for functions and attributes
3. Keep self as self
class MyClass:
# This works but isn't recommended
def my_method(kitty, attr):
kitty.attr = attr
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Best practices
1. Initialize attributes in __init__()
2. Naming
CamelCase for class, lower_snake_case for functions and attributes
3. self is self
4. Use docstrings
class MyClass:
"""This class does nothing"""
pass
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Let's practice!
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N