KEMBAR78
Python oop third class | PPTX
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
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
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

Python oop third class

  • 1.
  • 2.
    Agenda 1. ORM inPython 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 • Createclasses 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 withpeewee 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 theclass 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 modelof 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 modelof 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 modelof 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 thetable 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 afew 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 vscode 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 yourBus 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 thingsin OOP/ Python
  • 18.
  • 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)
  • 22.
  • 23.
    *args and **kvargs *argsand **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 isused 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 youto 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 learnedhow 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