SlideShare a Scribd company logo
OOP in Python
next steps
Agenda
1. ORM in Python with peewee
2. Useful tricks and helpers
• Properties (private attributes)
• Importing packages/functions
• *args
• **kwargs
Object-relational mapping (ORM)
• ORMs help you a lot in writing complex CRUD operations, which are a
pain to write via manual SQL
• Create a new object in a database
• Update an object in a database
• Delete an object from a databse
• We will use peewee in this course to try-out object-relationa
mapping: http://docs.peewee-orm.com/en/latest/
ZOO Animals
• Create classes that describe ZOO animals (name, rating) and store the
animals into a simple SQL database.
1.
Write the Class for Zoo Animal
2.
Write the SQL code for
creating a table, inserts,
deletes, saves
ORM Approach with peewee
1. Import peewee (install it through pip)
2. Set the database name
3. Create the class for the ZOO animals by inheriting from peewee.Model
4. Create the table for the class
5. Create a few instances of the ZOO animal
6. Save them in the database
1. Importing pewee & 2. Setting DB
# we first import the ORM
import peewee as pw
# we set the name of the Sqlite database
db = pw.SqliteDatabase('animals2.db')
3. Create the class for the ZooAnimal
class ZooAnimal(pw.Model):
"""
ORM model of the ZooAnimal
"""
animal_name = pw.TextField()
a_popular = pw.IntegerField() # 1 least, 5 most
class Meta:
'''
we connect the database to the models via the nested class
'''
database = db
class ZooAnimal(pw.Model):
"""
ORM model of the ZooAnimal
"""
animal_name = pw.TextField()
a_popular = pw.IntegerField() # 1 least, 5 most
class Meta:
'''
we connect the database to the models via the nested class
'''
database = db
We inherit from peewee.Model class
class ZooAnimal(pw.Model):
"""
ORM model of the ZooAnimal
"""
animal_name = pw.TextField()
a_popular = pw.IntegerField() # 1 least, 5 most
class Meta:
'''
we connect the database to the models via the nested class
'''
database = db
The attributes need to be of a type! http://docs.peewee-
orm.com/en/latest/peewee/models.html#field-types-table
Python oop   third class
class ZooAnimal(pw.Model):
"""
ORM model of the ZooAnimal
"""
animal_name = pw.TextField()
a_popular = pw.IntegerField() # 1 least, 5 most
class Meta:
'''
we connect the database to the models via the nested class
'''
database = db
Model configuration is kept namespaced in a special class called Meta
4. Creating the table for the Class
# Create the table if it does not exist yet
try:
ZooAnimal.create_table()
except pw.OperationalError:
print("ZooAnimal table already exists!")
5. Create a few instances of the ZOO animal
6. Save them into a database
animal1 = ZooAnimal(animal_name="Simon", a_popular=4)
animal2 = ZooAnimal(animal_name="Anton", a_popular=5)
animal3 = ZooAnimal(animal_name="Aleks", a_popular=2)
animal1.save()
animal2.save()
animal3.save()
*Install the vs code sqlite extension!
Other peewee things
• You can query for items in a database using .select()
• You can update items using .save()
• You can set primary and foreign keys
…
Exercise
1. Update your Bus model
(driver_name, number_of_seets)
to peewee model.
2. Create a few objects of type Bus.
3. Create a table for buses in the
code
4. Store your buses in the database
5. Explore the table
2. Usefull things in OOP/ Python
Private Attributes
Python oop   third class
Understanding: _, __, __str__
• _One underline in the beginning: private attribute, you should NOT
access it directly but rather through a method / property
• __two underlines in the beginning: you should not override this
method in a child class!
• __four__ underlines (2begining, 2 after): don’t call this method,
python does it for you.
Properties
class Celsius:
def __init__(self, temperature = 0):
self._temperature = temperature
def to_fahrenheit(self):
return (self.temperature * 1.8) + 32
@property
def temperature(self):
print("Getting value")
return self._temperature
@temperature.setter
def temperature(self, value):
if value < -273:
raise ValueError(”T below -273 is not possible")
print("Setting value")
self._temperature = value
c = Celsius(10)
print(c.temperature)
Importing…
*args and **kvargs
*args and **kwargs allow you to pass a variable number of arguments
to a function.
What variable means here is that you do not know beforehand how
many arguments can be passed to your function by the user.
http://book.pythontips.com/en/latest/args_and_kwargs.html
*argv
• *argv is used to pass a variable number of arguments without their
keys (names)
def test_variable_arguments(f_arg, *argv):
print("first normal arg:", f_arg)
for x in argv:
print("another arg through *argv:", x)
test_variable_arguments('Aleks', 'Anton', 'Nancy', 'Annabella')
**kvargs
**kwargs allows you to pass keyworded variable length of arguments
to a function.
def print_people(**kvargs):
for key,value in kvargs.items():
print("Key: {k}, Value: {v}".format(k=key, v=value))
people = {"Aleks": 28, "Anton": 28}
print_people(**people)
Summary
1. We learned how to implement ORM in Python using peewee
2. We discuss useful tricks and helpers
1. Properties
2. Importing packages/functions
3. *args
4. **kwargs
Check: https://github.com/google/styleguide

More Related Content

PDF
Object oriented approach in python programming
PPTX
Object Oriented Programming in Python
PPTX
Object oriented programming in python
PPTX
Multithreading in java
PPTX
Basics of Object Oriented Programming in Python
PPTX
Python Data-Types
PDF
Introduction to oops concepts
PPT
Basic concept of OOP's
Object oriented approach in python programming
Object Oriented Programming in Python
Object oriented programming in python
Multithreading in java
Basics of Object Oriented Programming in Python
Python Data-Types
Introduction to oops concepts
Basic concept of OOP's

What's hot (20)

PPTX
Chapter 05 classes and objects
PDF
C++ OOPS Concept
PPTX
File handling in Python
PPTX
Python – Object Oriented Programming
PPTX
This keyword in java
PPTX
Unit 4 python -list methods
PPTX
Class, object and inheritance in python
PPT
Object-oriented concepts
PPT
Introduction to oop
PPTX
Advance OOP concepts in Python
PDF
Data Science With Python
PPT
Basic concepts of object oriented programming
PPTX
Iterarators and generators in python
PPTX
Python Functions
PPTX
Array ppt
PPTX
List in Python
PPS
Java Exception handling
PPTX
Python-Classes.pptx
Chapter 05 classes and objects
C++ OOPS Concept
File handling in Python
Python – Object Oriented Programming
This keyword in java
Unit 4 python -list methods
Class, object and inheritance in python
Object-oriented concepts
Introduction to oop
Advance OOP concepts in Python
Data Science With Python
Basic concepts of object oriented programming
Iterarators and generators in python
Python Functions
Array ppt
List in Python
Java Exception handling
Python-Classes.pptx
Ad

Similar to Python oop third class (20)

PDF
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PDF
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PPT
2012 03 08_dbi
PPTX
Lecture-10_PHP-OOP.pptx
PPTX
Python_Unit_2 OOPS.pptx
PPTX
Bioinformatica p6-bioperl
PPTX
Bioinformatics p5-bioperl v2013-wim_vancriekinge
PPT
Spsl v unit - final
PPT
Spsl vi unit final
PPTX
Ground Gurus - Python Code Camp - Day 3 - Classes
PPTX
Python advance
PPTX
Bioinformatics p5-bioperlv2014
PPTX
Object oriented programming with python
PDF
Py.test
PPTX
Python_Object_Oriented_Programming.pptx
PPTX
Presentation_4516_Content_Document_20250204010703PM.pptx
PPTX
About Python
PPTX
Python 2. classes- cruciql for students objects1.pptx
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
2012 03 08_dbi
Lecture-10_PHP-OOP.pptx
Python_Unit_2 OOPS.pptx
Bioinformatica p6-bioperl
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Spsl v unit - final
Spsl vi unit final
Ground Gurus - Python Code Camp - Day 3 - Classes
Python advance
Bioinformatics p5-bioperlv2014
Object oriented programming with python
Py.test
Python_Object_Oriented_Programming.pptx
Presentation_4516_Content_Document_20250204010703PM.pptx
About Python
Python 2. classes- cruciql for students objects1.pptx
Ad

More from Aleksander Fabijan (10)

PPTX
Retrospective 1
PPTX
Python oop - class 2 (inheritance)
PPTX
Python oop class 1
PDF
Introduction to OOP in python inheritance
PPTX
Introduction to OOP in Python
PDF
The evolution of continuous experimentation in software product development: ...
PDF
Introduction to data visualisation with D3
PDF
JavaScript development methodology
PDF
Introduction to js (cnt.)
PDF
Javascript intro for MAH
Retrospective 1
Python oop - class 2 (inheritance)
Python oop class 1
Introduction to OOP in python inheritance
Introduction to OOP in Python
The evolution of continuous experimentation in software product development: ...
Introduction to data visualisation with D3
JavaScript development methodology
Introduction to js (cnt.)
Javascript intro for MAH

Recently uploaded (20)

PDF
Digital Strategies for Manufacturing Companies
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Become an Agentblazer Champion Challenge Kickoff
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Transform Your Business with a Software ERP System
PPTX
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
PDF
top salesforce developer skills in 2025.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
PDF
How to Confidently Manage Project Budgets
PDF
System and Network Administraation Chapter 3
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Best Practices for Rolling Out Competency Management Software.pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
medical staffing services at VALiNTRY
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
PPTX
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
PDF
Understanding Forklifts - TECH EHS Solution
Digital Strategies for Manufacturing Companies
How Creative Agencies Leverage Project Management Software.pdf
Become an Agentblazer Champion Challenge Kickoff
2025 Textile ERP Trends: SAP, Odoo & Oracle
Transform Your Business with a Software ERP System
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
top salesforce developer skills in 2025.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
How to Confidently Manage Project Budgets
System and Network Administraation Chapter 3
Upgrade and Innovation Strategies for SAP ERP Customers
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Best Practices for Rolling Out Competency Management Software.pdf
PTS Company Brochure 2025 (1).pdf.......
medical staffing services at VALiNTRY
A REACT POMODORO TIMER WEB APPLICATION.pdf
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
Understanding Forklifts - TECH EHS Solution

Python oop third class

  • 2. Agenda 1. ORM in Python with peewee 2. Useful tricks and helpers • Properties (private attributes) • Importing packages/functions • *args • **kwargs
  • 3. Object-relational mapping (ORM) • ORMs help you a lot in writing complex CRUD operations, which are a pain to write via manual SQL • Create a new object in a database • Update an object in a database • Delete an object from a databse • We will use peewee in this course to try-out object-relationa mapping: http://docs.peewee-orm.com/en/latest/
  • 4. ZOO Animals • Create classes that describe ZOO animals (name, rating) and store the animals into a simple SQL database. 1. Write the Class for Zoo Animal 2. Write the SQL code for creating a table, inserts, deletes, saves
  • 5. ORM Approach with peewee 1. Import peewee (install it through pip) 2. Set the database name 3. Create the class for the ZOO animals by inheriting from peewee.Model 4. Create the table for the class 5. Create a few instances of the ZOO animal 6. Save them in the database
  • 6. 1. Importing pewee & 2. Setting DB # we first import the ORM import peewee as pw # we set the name of the Sqlite database db = pw.SqliteDatabase('animals2.db')
  • 7. 3. Create the class for the ZooAnimal class ZooAnimal(pw.Model): """ ORM model of the ZooAnimal """ animal_name = pw.TextField() a_popular = pw.IntegerField() # 1 least, 5 most class Meta: ''' we connect the database to the models via the nested class ''' database = db
  • 8. class ZooAnimal(pw.Model): """ ORM model of the ZooAnimal """ animal_name = pw.TextField() a_popular = pw.IntegerField() # 1 least, 5 most class Meta: ''' we connect the database to the models via the nested class ''' database = db We inherit from peewee.Model class
  • 9. class ZooAnimal(pw.Model): """ ORM model of the ZooAnimal """ animal_name = pw.TextField() a_popular = pw.IntegerField() # 1 least, 5 most class Meta: ''' we connect the database to the models via the nested class ''' database = db The attributes need to be of a type! http://docs.peewee- orm.com/en/latest/peewee/models.html#field-types-table
  • 11. class ZooAnimal(pw.Model): """ ORM model of the ZooAnimal """ animal_name = pw.TextField() a_popular = pw.IntegerField() # 1 least, 5 most class Meta: ''' we connect the database to the models via the nested class ''' database = db Model configuration is kept namespaced in a special class called Meta
  • 12. 4. Creating the table for the Class # Create the table if it does not exist yet try: ZooAnimal.create_table() except pw.OperationalError: print("ZooAnimal table already exists!")
  • 13. 5. Create a few instances of the ZOO animal 6. Save them into a database animal1 = ZooAnimal(animal_name="Simon", a_popular=4) animal2 = ZooAnimal(animal_name="Anton", a_popular=5) animal3 = ZooAnimal(animal_name="Aleks", a_popular=2) animal1.save() animal2.save() animal3.save()
  • 14. *Install the vs code sqlite extension!
  • 15. Other peewee things • You can query for items in a database using .select() • You can update items using .save() • You can set primary and foreign keys …
  • 16. Exercise 1. Update your Bus model (driver_name, number_of_seets) to peewee model. 2. Create a few objects of type Bus. 3. Create a table for buses in the code 4. Store your buses in the database 5. Explore the table
  • 17. 2. Usefull things in OOP/ Python
  • 20. Understanding: _, __, __str__ • _One underline in the beginning: private attribute, you should NOT access it directly but rather through a method / property • __two underlines in the beginning: you should not override this method in a child class! • __four__ underlines (2begining, 2 after): don’t call this method, python does it for you.
  • 21. Properties class Celsius: def __init__(self, temperature = 0): self._temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 @property def temperature(self): print("Getting value") return self._temperature @temperature.setter def temperature(self, value): if value < -273: raise ValueError(”T below -273 is not possible") print("Setting value") self._temperature = value c = Celsius(10) print(c.temperature)
  • 23. *args and **kvargs *args and **kwargs allow you to pass a variable number of arguments to a function. What variable means here is that you do not know beforehand how many arguments can be passed to your function by the user. http://book.pythontips.com/en/latest/args_and_kwargs.html
  • 24. *argv • *argv is used to pass a variable number of arguments without their keys (names) def test_variable_arguments(f_arg, *argv): print("first normal arg:", f_arg) for x in argv: print("another arg through *argv:", x) test_variable_arguments('Aleks', 'Anton', 'Nancy', 'Annabella')
  • 25. **kvargs **kwargs allows you to pass keyworded variable length of arguments to a function. def print_people(**kvargs): for key,value in kvargs.items(): print("Key: {k}, Value: {v}".format(k=key, v=value)) people = {"Aleks": 28, "Anton": 28} print_people(**people)
  • 26. Summary 1. We learned how to implement ORM in Python using peewee 2. We discuss useful tricks and helpers 1. Properties 2. Importing packages/functions 3. *args 4. **kwargs Check: https://github.com/google/styleguide