Hi and Enjoy

Today

  • Classes
  • Inheritance
  • Decorators
  • Datetime

Little quiz

How do you open

Zen of Python

>>> import that
>>> import this
>>> import zen_of_python
>>> <?php
namespace python;
use Zen/Python as ZenOfPython; ?>

A.

B.

C.

D.

How do you print a list of employees one by one

>>> print "%s\n" % employee for employee in list_of_employees
>>> print "\n".join(list_of_employees)
>>> print list_of_employees.join("\n")
>>> print "a list of employees one by one"

A.

B.

C.

D.

How to make a dict from my_list = [('one', 1), ('two', 2)]

>>> my_dict = {}
>>> for key, value in my_list:
        my_dict[key] = value
>>> my_dict = dict(my_list)
>>> my_dict = {key: value for (key, value) in my_list}
>>> sudo make my_dict

A.

B.

C.

D.

Which one would print "hello, my name is truthy"

>>> if [] is False:
        print "hello, my name is truthy"
>>> if "test" is True:
        print "hello, my name is truthy"
>>> if [] is not None:
        print "hello, my name is truthy"
>>> if what is love:
        print "hello, my name is truthy"

A.

B.

C.

D.

How do you declare a function dice_roll returning 4

>>> def dice_roll:
        return 4
>>> fun dice_roll:
        return 4
>>> def dice_roll():
        return 4
>>> int dice_roll() {
        int roll = 4;
        return roll;
}

A.

B.

C.

D.

Classes

>>> class ShoppingItem(object):
        name = None
        price = None
        description = ''

Classes

>>> class ShoppingItem(object):
        def __init__(self, name, price, description=''):
            self.name = name
            self.price = price
            self.description = description

Classes

>>> class ShoppingItem(object):
        def __init__(self, name, price, description=''):
            self.name = name
            self.price = price
            self.description = description

        def __str__(self):
            return "%s (%s)" % (self.name, self.description)

Classes

>>> shopping_item = ShoppingItem('chair', 100)
>>> shopping_item
<__main__.ShoppingItem object at 0x0000000002F14D30>
>>> print shopping_item
chair ()

Classes

>>> class ShoppingItem(object):
        def __init__(self, name, price, description=''):
            self.name = name
            self.price = price
            self.description = description

        def __str__(self):
            if self.description:
                return "%s (%s)" % (self.name, self.description)
            else:
                return self.name

Classes

>>> chair = ShoppingItem('chair', 100)
>>> screen = ShoppingItem('screen', 650, 'IIYAMA HD')
>>> print chair
chair
>>> print screen
screen (IIYAMA HD)
>>> print chair.price
100
>>> print vars(screen)
{'price': 650, 'name': 'screen', 'description': 'IIYAMA HD'}

Classes

>>> vars(ShoppingItem)
dict_proxy({
    '__module__': '__main__',
    '__str__': <function __str__ at 0x0000000002F163C8>,
    '__dict__': <attribute '__dict__' of 'ShoppingItem' objects>,
    '__weakref__': <attribute '__weakref__' of 'ShoppingItem' objects>,
    '__doc__': None,
    '__init__': <function __init__ at 0x0000000002F16358>
})

Classes

>>> class ShoppingItem(object):
        """Class used to represent shopping objects.

        Arguments:
        name (str) - used to represent shopping item
        price (Decimal) - the price of item in PLN

        Keyword arguments:
        description (str) - full item description
        """
        def __init__(self, name, price, description=''):
            self.name = name
            self.price = price
            self.description = description

        def __str__(self):
            if self.description:
                return "%s (%s)" % (self.name, self.description)
            else:
                return self.name

Classes

>>> print vars(ShoppingItem)['__doc__']
Class used to represent shopping objects.

        Arguments:
        name (str) - used to represent shopping item
        price (Decimal) - the price of item in PLN

        Keyword arguments:
        description (str) - full item description

Classes

>>> class ShoppingItem(object):
        """Class used to represent shopping objects."""

        def __init__(self, name, price, description=''):
            self.name = name
            self.price = price
            self.description = description

        def __str__(self):
            if self.description:
                return "%s (%s)" % (self.name, self.description)
            else:
                return self.name

        def sale(self, percentage):
            self.price *= (100 - percentage) / 100

Classes

>>> shopping_item = ShoppingItem(
        'MacBook adapter', 180,
        "why so expensive?")
>>> print shopping_item.price
180
>>> shopping_item.sale(20)
>>> print shopping_item.price
144

Classes

>>> shopping_item = ShoppingItem(
        'MacBook adapter', 180,
        "why so expensive?")
>>> print shopping_item.price
180
>>> shopping_item.sale(20)
>>> print shopping_item.price
144


>>> shopping_item.price = 1
>>> print shopping_item.price
0

Classes

>>> class ShoppingItem(object):
        """Class used to represent shopping objects."""

        def __init__(self, name, price, description=''):
            self.name = name
            self.price = price
            self.description = description

        def __str__(self):
            if self.description:
                return "%s (%s)" % (self.name, self.description)
            else:
                return self.name

        def sale(self, percentage):
            self.price *= (100 - percentage) / 100.

Magic Methods

__new__(cls)
__init__(self)
__del__(self)


__cmp__(self, other)
__eq__(self, other)
__ne__(self, other)
__lt__(self, other)
__gt__(self, other)
__le__(self, other)
__ge__(self, other)

Magic Methods

__int__(self)
__long__(self)
__float__(self)
__complex__(self)
__oct__(self)
__hex__(self)


__str__(self)
__repr__(self)
__unicode__(self)
__format__(self, formatstr)
__hash__(self)
__nonzero__(self)
__dir__(self)
__sizeof__(self)

Task

Task

>>> class Order(object):
        ...

>>> my_order = Order("keyboard", "JW")
>>> print my_order
JW orders keyboard (Status: Created)
>>> my_order.confirm_by()
Order must be confirmed by authorized person.
>>> my_order.confirm_by("Postman")
Postman is not an authorized person. Order must be confirmed by authorized person.
>>> my_order.confirm_by("RS")
>>> print my_order
JW orders keyboard (Status: Confirmed)
>>> other_order = my_order.make_similiar_for("ŁG")
>>> print other_order
ŁG orders keyboard (Status: Created)

>>> my_order.finish()
>>> print my_order.status
finished

Task

class Order(object):
    def __init__(self, name, ordering):
            self.name = name
            self.ordering = ordering
            self.status = 'created'

    def __str__(self):
            return "%s orders %s (Status: %s)" % (self.ordering, self.name, self.status.capitalize())
    
    def confirm_by(self, confirmator=None):
            if not confirmator:
                    print "Order must be confirmed by authorized person."
            elif confirmator != "RS":
                    print "%s is not an authorized person. Order must be confirmed by authorized person." % (confirmator)
            else:
                    self.status = 'confirmed'

    def make_similiar_for(self, new_name):
            return Order(new_name, self.ordering)

    def finish(self):
            self.status = 'finished'

Getter/Setters

class Order(object):
    _name = None
    status = None

    def __init__(self, name, ordering):
            self.name = name
            self.ordering = ordering
            self.status = 'created'

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if self.status in ['confirmed', 'finished']:
            print "Can not edit order with status %s" % self.status
        self._name = value

Getter/Setters

>>> my_order = Order("keyboard", "JW")
>>> print my_order
JW orders keyboard (Status: Created)
>>> my_order.name = "mouse"
>>> print my_order
JW orders mouse (Status: Created)
>>> my_order.confirm_by("RS")
>>> my_order.name = "new plasma TV"
Can not edit order with status confirmed

Decorators

>>> class Order(object):
        @property
        def price(self):
            return self.net_value * 0.19 + self.post_costs


        @classmethod
        def generate_list_of_orders(cls, ordering, names):
            return [cls(name, ordering) for name in names]

Decorators

>>> my_orders = Order.generate_list_of_orders(
        "JW", ["notebook", "keyboard", "mouse"])
>>> print my_orders
[<__main__.Order object at 0x7fedc6a6e4d0>,
<__main__.Order object at 0x7fedc6a6e510>,
<__main__.Order object at 0x7fedc6a6e550>]

Decorators

class Order(object):
    status = None

    def __init__(self, name, ordering):
            self.name = name
            self.ordering = ordering
            self.status = 'created'
  
    def __repr__(self):
            return "%s (%s)" % (self.name, self.ordering)

Decorators

>>> my_orders = Order.generate_list_of_orders(
        "JW", ["notebook", "keyboard", "mouse"])
>>> print my_orders
[notebook (JW), keyboard (JW), mouse (JW)]

Decorators

>>> class Order(object):
        @staticmethod
        def get_current_company():
            return "Grand Parade"


>>> my_order = Order('mouse', 'JW')
>>> print Order.get_current_company()
Grand Parade
>>> print my_order.get_current_company()
Grand Parade

Inheritance

>>> class A(object):
...     descriptor = "a"
... 
>>> class B(A):
...     descriptor = "b"
... 
>>> class C(A):
...     pass
... 
>>> class D(B, C):
...     pass
... 
>>> class E(C, B):
...     pass
... 

Inheritance

>>> A.descriptor
'a'
>>> B.descriptor
'b'
>>> C.descriptor
'a'
>>> D.descriptor
'b'
>>> E.descriptor
'b'
>>> E.mro()
[<class '__main__.E'>, <class '__main__.C'>, 
<class '__main__.B'>, <class '__main__.A'>, 
<type 'object'>]

Everything's an object!

>>> def class_generator(class_type):
...     if class_type == "foo":
...             class Foo(object):
...                     def whoami(self):
...                             return "foo"
...             return Foo
...     elif class_type == "bar":
...             class Bar(object):
...                     def whoami(self):
...                             return "bar"
...             return Bar
...
>>> def give_me_many_class_instances(types):
...     return [class_generator(class_type)() for class_type in types]

>>> print [instance.whoami() for instance in \
        give_me_many_class_instances(['foo', 'foo', 'bar', 'foo'])]
['foo', 'foo', 'bar', 'foo']

>>> print [instance for instance in \
        give_me_many_class_instances(['foo', 'foo', 'bar', 'foo'])]
[<__main__.Foo object at 0x7ff880500a10>, <__main__.Foo object at 0x7ff880500a50>,
<__main__.Bar object at 0x7ff880500a50, <__main__.Foo object at 0x7ff880500ad0>]

Datetime

>>> import datetime

>>> datetime.date
<type 'datetime.date'>

>>> datetime.datetime
<type 'datetime.datetime'>

>>> datetime.time
<type 'datetime.time'>

>>> datetime.timedelta
<type 'datetime.timedelta'>

datetime.date

>>> my_date = datetime.date(2014, 12, 15)
>>> print my_date
2014-12-15
>>> my_date.day
15
>>> my_date.weekday()
0
>>> datetime.date.today()
datetime.date(2014, 12, 16)

datetime.datetime

>>> my_date = datetime.datetime(2014, 12, 15)
>>> print my_date
2014-12-15 00:00:00
>>> my_date = datetime.datetime(2014, 12, 15, 12, 5, 10, 1023)
>>> print my_date
2014-12-15 12:05:10.001023

>>> print datetime.datetime.now()
2014-12-16 13:34:40.857869
>>> print datetime.datetime.utcnow()
2014-12-16 12:34:48.362744
>>> print datetime.datetime.now().tzinfo
None
>>> print datetime.datetime.utcnow().tzinfo
None

datetime.time

>>> print datetime.time()
00:00:00
>>> print datetime.time(12, 15, 12)
12:15:12

datetime.timedelta

>>> datetime.datetime.now() - datetime.datetime(2008, 1, 1)
datetime.timedelta(2541, 49350, 263489)
>>> time_passed = _
>>> time_passed.days
2541
>>> time_passed.seconds
49350
>>> time_passed.microseconds
263489
>>> time_passed.minutes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'datetime.timedelta' object has no attribute 'minutes'
>>> time_passed.total_seconds()
219591750.263489

datetime.timedelta

>>> def add_day_and_hour(given_date):
...     return given_date + datetime.timedelta(1, 60*60)
... 
>>> print add_day_and_hour(datetime.datetime.now())
2014-12-17 14:47:09.957245
>>> print add_day_and_hour(datetime.date.today())
2014-12-17

stftime, strptime

>>> hobbit_premiere = datetime.datetime(2014, 12, 25, 17, 00)
>>> hobbit_premiere.strftime("%Y-%m-%d")
'2014-12-25'
>>> print hobbit_premiere.strftime("In the year %Y on the day of \
%d.%m the story would find its end and at %I %p")
In the year 2014 on the day of 25.12 the story would find its end and at 05 PM


>>> datetime.datetime.strptime("spam 2014 spamspam01spamspam spam day 20", 
        "spam %Y spamspam%mspamspam spam day 20")
datetime.datetime(2014, 1, 1, 0, 0)


>>> datetime.datetime.strptime("2014/07/01 12.30.15", 
        "%Y/%m/%d %H.%M.%S").strftime("%Y-%m-%d")
'2014-07-01'

Task 2 (and you're free to go)

>>> from datetime_logger import Logger
>>> my_logger = Logger()
>>> print my_logger.creation_date
2014-12-16 15:04:02.621560
>>> my_logger.log_task('eating sandwich', 15)
>>> my_logger.log_task('solving GPS', 60)
>>> my_logger.log_task('playing fifa', 12)
>>> print my_logger.list_tasks()
['eating sandwich', 'solving GPS', 'playing fifa']
>>> print my_logger.all_time
1:27:00
>>> print my_logger.time_left(hours_of_work=6)
4:33:00
>>> print my_logger.generate_report()
2014 reports: 12/14
eating sandwich - 0:15
solving GPS - 1:0
playing fifa - 0:12
Sum: 1:27
from datetime import datetime, timedelta

class Logger(object):
        def __init__(self):
                self.creation_date = datetime.now()
                self.tasks = []

        def log_task(self, task, time_taken):
                self.tasks.append({
                        'name': task,
                        'time': timedelta(minutes=time_taken)
                })
                return self.tasks[-1]

        def list_tasks(self):
                return [task['name'] for task in self.tasks]

        @property
        def all_time(self):
                return sum([task['time'] for task in self.tasks], timedelta())

        def time_left(self, hours_of_work=8):
                return timedelta(hours=hours_of_work) - self.all_time

        def generate_report(self):
                report = []
                report.append(self.creation_date.strftime("%Y reports: %m/%y"))
                for task in self.tasks:
                        report.append("%s - %s:%s" % (task['name'], task['time'].seconds//3600, task['time'].seconds//60%60))
                report.append("Sum: %s:%s" % (self.all_time.seconds//3600, self.all_time.seconds//60%60))
                return "\n".join(report)

As promised

you're free to go :)

 

Thanks!

Python School #4

By Kuba Wasielak

Python School #4

  • 828