Congratulations

Introduction to Object-Oriented Programming in Python

George Boorman

Curriculum Manager, DataCamp

Classes and objects

Term Definition
Class A blueprint/template used to build objects
Object A combination of data and functionality; An instance of a class
Introduction to Object-Oriented Programming in Python

Attributes and methods

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

Core concepts

Encapsulation:

  • Bundling of data and methods

Inheritance:

  • Extending the functionality of existing code

Polymorphism:

  • Creating a unified interface
Introduction to Object-Oriented Programming in Python

Comparisons

Operator Method
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
Introduction to Object-Oriented Programming in Python

String representation

__str__()

  • print(obj), str(obj)
print([1,2,3])
[1 2 3]
str([1,2,3])
'[1, 2, 3]' 
  • informal, for end user
  • string representation

__repr__()

  • repr(obj), printing in console
repr([1,2,3])
[1,2,3]
[1,2,3]
[1,2,3]
  • formal, for developer
  • reproducible representation
  • fallback for print()
Introduction to Object-Oriented Programming in Python

Error-handling

class BalanceError(Exception): 
    pass

class Customer: def __init__(self, name, balance): if balance < 0 : raise BalanceError("Balance has to be non-negative!") else: self.name, self.balance = name, balance
# Use try-except to catch errors try: cust = Customer("Larry Torres", -100) except BalanceError: cust = Customer("Larry Torres", 0)
Introduction to Object-Oriented Programming in Python

Where to next?

  • Multiple inheritance
  • Descriptors
  • Custom attributes
  • Custom iterators
  • Type hints
  • Abstract base classes
Introduction to Object-Oriented Programming in Python

Let's practice!

Introduction to Object-Oriented Programming in Python

Preparing Video For Download...