[go: up one dir, main page]

0% found this document useful (0 votes)
49 views30 pages

1 Chapter

Object-oriented programming (OOP) involves organizing code into objects that contain both data (attributes) and behaviors (methods). In Python, classes are used as blueprints to create objects. The __init__() method is a special method that is called whenever a new object is instantiated from a class, and is used to initialize attributes. It allows attributes to be set upon object creation rather than later via separate methods. This provides a cleaner way to ensure objects are properly initialized with all required attributes from the start.

Uploaded by

vlasvlasvlas
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)
49 views30 pages

1 Chapter

Object-oriented programming (OOP) involves organizing code into objects that contain both data (attributes) and behaviors (methods). In Python, classes are used as blueprints to create objects. The __init__() method is a special method that is called whenever a new object is instantiated from a class, and is used to initialize attributes. It allows attributes to be set upon object creation rather than later via separate methods. This provides a cleaner way to ensure objects are properly initialized with all required attributes from the start.

Uploaded by

vlasvlasvlas
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
You are on page 1/ 30

What is OOP?

OBJ E C T-OR IE N TE D P R OG R AMMIN G IN P YTH ON

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])
np.mean function
print(type(a))
... ...

numpy.ndarray

OBJECT-ORIENTED PROGRAMMING IN PYTHON


Attributes and methods
State ↔ a ributes 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 a ributes and


methods

OBJECT-ORIENTED PROGRAMMING IN PYTHON


Object = attributes + methods
a ribute ↔ 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!
OBJ E C T-OR IE N TE D P R OG R AMMIN G IN P YTH ON
Class anatomy:
attributes and
methods
OBJ E C T-OR IE N TE D P R OG R AMMIN G IN P YTH ON

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

use ClassName() to create an object of


c1 = Customer()
class ClassName
c2 = Customer()

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 a ribute

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!
OBJ E C T-OR IE N TE D P R OG R AMMIN G IN P YTH ON
Class anatomy: the
__init__
constructor
OBJ E C T-OR IE N TE D P R OG R AMMIN G IN P YTH ON

Alex Yarosh
Content Quality Analyst @ DataCamp
Methods and attributes
Methods are function de nitions within a class MyClass:
class # function definition in class
# first argument is self
self as the rst argument
def my_method1(self, other_args...):
De ne a ributes by assignment # do things here

Refer to a ributes 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 a ributes
obj = MyClass() a ributes 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 a ributes in __init__()

OBJECT-ORIENTED PROGRAMMING IN PYTHON


Best practices
1. Initialize a ributes in __init__()

2. Naming
CamelCase for classes, lower_snake_case for functions and a ributes

OBJECT-ORIENTED PROGRAMMING IN PYTHON


Best practices
1. Initialize a ributes in __init__()

2. Naming
CamelCase for class, lower_snake_case for functions and a ributes

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 a ributes in __init__()

2. Naming
CamelCase for class, lower_snake_case for functions and a ributes

3. self is self

4. Use docstrings
class MyClass:
"""This class does nothing"""
pass

OBJECT-ORIENTED PROGRAMMING IN PYTHON


Let's practice!
OBJ E C T-OR IE N TE D P R OG R AMMIN G IN P YTH ON

You might also like