Structures

Classes


In [1]:
class MyOwnClass(object):
    """
    This is a documentation for my class, so anyone can read it.
    """
    CLASS_CONST = 42
    
    def __init__(self, argument1, default_argument2=1):
        """
        This is a constructor of MyOwnClass. It saves all arguments
        as a 'protected' variables of a class.
        """
        self._argument1 = argument1
        self._argument2 = default_argument2
        super(MyOwnClass, self).__init__()
    
    def get_info(self):
        return ("Class const = %d\nArgument1 = %s\nArgument2 = %d" 
              % (self.CLASS_CONST, self.argument1, self.argument2))
    
    def print_all(self):
        print(self.get_info())
        
    @property
    def argument1(self):
        return self._argument1
    
    @property
    def argument2(self):
        return 2**self._argument2

In [2]:
instance_of_my_own_class_1 = MyOwnClass('string arg #1') 
instance_of_my_own_class_1.print_all()


Class const = 42
Argument1 = string arg #1
Argument2 = 2

In [3]:
instance_of_my_own_class_2 = MyOwnClass('string arg #1', 2)
instance_of_my_own_class_2.print_all()


Class const = 42
Argument1 = string arg #1
Argument2 = 4

In [4]:
instance_of_my_own_class_3 = MyOwnClass('string arg #1', default_argument2=4)
instance_of_my_own_class_3.print_all()


Class const = 42
Argument1 = string arg #1
Argument2 = 16

In [5]:
instance_of_my_own_class_4 = MyOwnClass(default_argument2=5, argument1=1)
instance_of_my_own_class_4.print_all()


Class const = 42
Argument1 = 1
Argument2 = 32

In [6]:
instance_of_my_own_class_5 = MyOwnClass('string arg #1', 'string')
instance_of_my_own_class_5.print_all()


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-c830f338182f> in <module>()
      1 instance_of_my_own_class_5 = MyOwnClass('string arg #1', 'string')
----> 2 instance_of_my_own_class_5.print_all()

<ipython-input-1-0519913862fc> in print_all(self)
     19 
     20     def print_all(self):
---> 21         print(self.get_info())
     22 
     23     @property

<ipython-input-1-0519913862fc> in get_info(self)
     16     def get_info(self):
     17         return ("Class const = %d\nArgument1 = %s\nArgument2 = %d" 
---> 18               % (self.CLASS_CONST, self.argument1, self.argument2))
     19 
     20     def print_all(self):

<ipython-input-1-0519913862fc> in argument2(self)
     27     @property
     28     def argument2(self):
---> 29         return 2**self._argument2

TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'

Magic methods

There are a bunch of magic methods available in Python. You can overide some of them:

  • __init__
  • __unicode__
  • __str__
  • __getattr__
  • __setattr__
  • __gt__
  • __gte__
  • __lt__
  • __lte__
  • ...

In [7]:
dir(instance_of_my_own_class_1)


Out[7]:
['CLASS_CONST',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_argument1',
 '_argument2',
 'argument1',
 'argument2',
 'get_info',
 'print_all']

In [8]:
instance_of_my_own_class_1.__dict__


Out[8]:
{'_argument1': 'string arg #1', '_argument2': 1}

Iterators & Generators


In [9]:
[i*10 for i in range(10)]


Out[9]:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

In [10]:
(i*10 for i in range(10))


Out[10]:
<generator object <genexpr> at 0x1041af410>

In [11]:
list((i*10 for i in range(10)))


Out[11]:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

In [12]:
{i / 2 for i in range(10)}


Out[12]:
{0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5}

In [13]:
set([1,2,3,1,2,3])


Out[13]:
{1, 2, 3}

In [14]:
{i: (i - 2, i**2) for i in range(10)}


Out[14]:
{0: (-2, 0),
 1: (-1, 1),
 2: (0, 4),
 3: (1, 9),
 4: (2, 16),
 5: (3, 25),
 6: (4, 36),
 7: (5, 49),
 8: (6, 64),
 9: (7, 81)}

In [15]:
dict((i, i**i) for i in range(10))


Out[15]:
{0: 1,
 1: 1,
 2: 4,
 3: 27,
 4: 256,
 5: 3125,
 6: 46656,
 7: 823543,
 8: 16777216,
 9: 387420489}

In [16]:
map(lambda x: x*10, range(10))


Out[16]:
<map at 0x1041c2da0>

In [17]:
from functools import reduce

reduce(lambda prev_result, item: prev_result * item, range(1, 5))


Out[17]:
24

In [18]:
{i: i**2 for i in range(10) if i % 3 == 0}


Out[18]:
{0: 0, 3: 9, 6: 36, 9: 81}

In [19]:
[(a, b) for a in range(4) for b in range(0, -a, -1)]


Out[19]:
[(1, 0), (2, 0), (2, -1), (3, 0), (3, -1), (3, -2)]

In [20]:
[1] * 10


Out[20]:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

In [21]:
[[1] * 5] * 5


Out[21]:
[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1]]

In [22]:
matrix = [[1] * 5] * 5
matrix


Out[22]:
[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1]]

In [23]:
matrix[3][2] = 2

In [24]:
matrix


Out[24]:
[[1, 1, 2, 1, 1],
 [1, 1, 2, 1, 1],
 [1, 1, 2, 1, 1],
 [1, 1, 2, 1, 1],
 [1, 1, 2, 1, 1]]

In [25]:
matrix = [[1] * 5 for i in range(5)]
matrix


Out[25]:
[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1]]

In [26]:
matrix[3][2] = 2

In [27]:
matrix


Out[27]:
[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 2, 1, 1],
 [1, 1, 1, 1, 1]]

Tricks in functions (class methods)


In [28]:
DEFAULT_LOGIN = 'root'

def my_function(arg1, arg2, arg3='str', arg4=None):
    if arg4 is None:
        arg4 = {}
    if 'login' not in arg4:
        arg4['login'] = DEFAULT_LOGIN
    if 'id' not in arg4:
        arg4['id'] = 0
    else:
        arg4['id'] += 1
    print(arg1, arg2, arg3, arg4)

In [29]:
my_function(1, 2)


1 2 str {'id': 0, 'login': 'root'}

In [30]:
args = [10, 20]
kwargs = {
    'arg3': 'unicode',
    'arg4': {'login': 'frol', 'password': '$(KE)@D)$!1'},
}

In [31]:
my_function(*args, **kwargs)


10 20 unicode {'id': 0, 'password': '$(KE)@D)$!1', 'login': 'frol'}

In [32]:
my_function(*args, **kwargs)


10 20 unicode {'id': 1, 'password': '$(KE)@D)$!1', 'login': 'frol'}

In [33]:
kwargs


Out[33]:
{'arg3': 'unicode',
 'arg4': {'id': 1, 'login': 'frol', 'password': '$(KE)@D)$!1'}}

In [34]:
kwargs = {
    'arg1': 11,
    'arg2': 22,
    'arg3': 'unicode',
    'arg4': {'login': 'frol', 'password': '$(KE)@D)$!1'},
}

In [35]:
my_function(**kwargs)


11 22 unicode {'id': 0, 'password': '$(KE)@D)$!1', 'login': 'frol'}

In [36]:
kwargs


Out[36]:
{'arg1': 11,
 'arg2': 22,
 'arg3': 'unicode',
 'arg4': {'id': 0, 'login': 'frol', 'password': '$(KE)@D)$!1'}}

In [37]:
def my_function2(*args, **kwargs):
    login = DEFAULT_LOGIN
    if 'arg4' in kwargs and 'login' in kwargs['arg4']:
        login = kwargs['arg4']['login']
    kwargs['arg3'] = login
    my_function(*args, **kwargs)

In [38]:
my_function2(**kwargs)


11 22 frol {'id': 1, 'password': '$(KE)@D)$!1', 'login': 'frol'}