0% found this document useful (0 votes)
2 views35 pages

Chapter 1

The document provides an introduction to Object-Oriented Programming (OOP) in Python, contrasting it with procedural programming. It explains key concepts such as classes, objects, attributes, and methods, emphasizing the importance of maintainable and reusable code. Additionally, it covers best practices for defining classes and initializing attributes.

Uploaded by

Doménica Amores
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views35 pages

Chapter 1

The document provides an introduction to Object-Oriented Programming (OOP) in Python, contrasting it with procedural programming. It explains key concepts such as classes, objects, attributes, and methods, emphasizing the importance of maintainable and reusable code. Additionally, it covers best practices for defining classes and initializing attributes.

Uploaded by

Doménica Amores
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is OOP?

I N T R O D U C T I O N T O 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

George Boorman
Curriculum Manager, DataCamp
Procedural programming

Code as a sequence of steps

Great for data analysis

1 Image source: [Link]

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Thinking in sequences

INTRODUCTION TO 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 Great for building software

Maintainable and reusable code!

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Objects
Object = data + functionality

State - an object's data

Behavior - an object's functionality

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Objects in Python
Everything in Python is an object Object Type
5 int

"Hello" str

[Link]() DataFrame

sum() function

... ...

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Classes as blueprints
Class: a blueprint for objects outlining possible states and behaviors

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Classes as blueprints
Class : a blueprint for objects outlining possible states and behaviors

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Classes in Python
Python objects of the same type behave in the same way

lists are a class


Created with comma-separated values [1, 2, 3, 4, 5]

Share the same methods, e.g., .append()

Use type() to find the class

type([1, 2, 3, 4, 5])

<class 'list'>

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Attributes and methods
State ↔ attributes Behavior ↔ methods
import pandas as pd import pandas as pd
df = [Link]({"a": [1,2,3], df = [Link]({"a": [1,2,3],
"b": [4,5,6]}) "b": [4,5,6]})
# shape attribute # head method
[Link] [Link]()

(3, 2) a b
0 1 4
Use obj. to access attributes and 1 2 5
methods 2 3 6

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Displaying attributes and methods
# Display attributes and methods # Display attributes and methods
dir([1, 2, 3, 4]) dir(list)

['__add__', ['__add__',
'__class__', '__class__',
'__contains__', '__contains__',
'__delattr__', '__delattr__',
... ...
'pop', 'pop',
'remove', 'remove',
'reverse', 'reverse',
'sort'] 'sort']

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Cheat sheet
Term Definition
Class A blueprint/template used to build objects
Object A combination of data and functionality; An instance of a class
State Data associated with an object, assigned through attributes
Behavior An object's functionality, defined through methods

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Let's review!
I N T R O D U C T I O N T O 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
I N T R O D U C T I O N T O 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

George Boorman
Curriculum Manager, DataCamp
A Customer class
class <name>: starts a class definition
class Customer:
# Code for class goes here Code inside class is indented
pass
Use pass to create an "empty" class

c_one = Customer()
Use ClassName() to create an object of
class ClassName
c_two = Customer()

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Add methods to a class
Method definition = function definition
class Customer:
def identify(self, name):
within class

print("I am Customer " + name) Use self as the first argument in method
definition

cust = Customer()
Ignore self when calling a method on an
object
[Link]("Laura")

I am Customer Laura

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


class Customer:
def identify(self, name):
print("I am Customer " + name)

cust = Customer()
[Link]("Laura")

What is self?
Classes are templates

self should be the first argument of any method

self is a stand-in for a (not yet created) object

[Link]("Laura") will be interpreted as [Link](cust, "Laura")

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


We need attributes
OOP bundles data with methods that operate on data
Customer 's' name should be an attribute

Attributes are created by assignment (=) in methods

INTRODUCTION TO 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
# Will create .name when set_name is called
[Link] = new_name
# Create an object
# .name doesn't exist here yet
cust = Customer()
# .name is created and set to "Lara de Silva"
cust.set_name("Lara de Silva")
print([Link])

Lara de Silva

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Old version New version
class Customer: class Customer:
def set_name(self, new_name):
[Link] = 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" + [Link])

cust = Customer() cust = Customer()


cust.set_name("Rashid Volkov")
[Link]("Eris Odoro") [Link]()

I am Customer Eris Odoro I am Customer Rashid Volkov

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Let's practice!
I N T R O D U C T I O N T O 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
I N T R O D U C T I O N T O 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

George Boorman
Curriculum Manager, DataCamp
Methods and attributes
Methods are function definitions within a class MyClass:
class # function definition in class
# first argument is self
self as the first argument
def my_method1(self, other_args...):
Define attributes by assignment # do things here
def my_method2(self, my_attr):
Refer to attributes in class via self.___
# attribute created by assignment
Calling lots of methods could become self.my_attr = my_attr
unsustainable! ...

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Constructor
Add data to object when creating it
Constructor __init__() method is called every time an object is created
Called automatically because of __methodname__ syntax

class Customer:
def __init__(self, name):
# Create the .name attribute and set it to name parameter
[Link] = name
print("The __init__ method was called")

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Constructor
# __init__ is implicitly called
cust = Customer("Lara de Silva")
print([Link])

The __init__ method was called


Lara de Silva

INTRODUCTION TO 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)
...
Generally we should use the constructor
obj = MyClass()
Attributes are created when the object is
# attr1 created
obj.my_method1(val1)
created
# attr2 created More usable and maintainable code
obj.my_method2(val2)

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Add arguments
class Customer:
# Add balance argument
def __init__(self, name, balance):
[Link] = name

# Add the balance attribute


[Link] = balance
print("The __init__ method was called")

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Add parameters
# __init__ is called
cust = Customer("Lara de Silva", 1000)
print([Link])
print([Link])

The __init__ method was called


Lara de Silva
1000

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Default arguments
class Customer:
# Set a default value for balance
def __init__(self, name, balance=0):
[Link] = name
# Assign the new attribute
[Link] = balance
print("The __init__ method was called")

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Default arguments
# Don't specify the balance explicitly
cust = Customer("Lara de Silva")
print([Link])
# The balance attribute is created anyway
print([Link])

The __init__ method was called


Lara de Silva
0

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Best practices
1. Initialize attributes in __init__()

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Best practices
1. Initialize attributes in __init__()

2. Naming
CamelCase for classes, lower_snake_case for functions and attributes

INTRODUCTION TO 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(george, attr):
[Link] = attr

INTRODUCTION TO 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

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON


Let's practice!
I N T R O D U C T I O N T O 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

You might also like