Wiederholung

[6]:
v = 666
[2]:
type(v)
[2]:
int
[9]:
v = 1.234
[5]:
type(v)
[5]:
float
[11]:
v = [1, 2.5, 'drei', {1: 'eins', 2: 'zwei'}]
[13]:
type(v)
[13]:
list

Mutable/Immutable

[14]:
l = [1,2,'drei']
[15]:
l.append('vier')
[17]:
l
[17]:
[1, 2, 'drei', 'vier']
[19]:
t = (1,2,'drei')
[20]:
type(t)
[20]:
tuple
[23]:
try:
    t.append('vier')
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'tuple' object has no attribute 'append'

Attribute

[24]:
l.append(5.0)
[25]:
import sys
[26]:
type(sys)
[26]:
module
[27]:
sys.platform
[27]:
'linux'
[28]:
sys.argv
[28]:
['/home/jfasch/venv/jfasch-home/lib64/python3.9/site-packages/ipykernel_launcher.py',
 '-f',
 '/home/jfasch/.local/share/jupyter/runtime/kernel-51139385-5832-4866-9768-77397a312b47.json']
[30]:
help(sys)
Help on built-in module sys:

NAME
    sys

MODULE REFERENCE
    https://docs.python.org/3.9/library/sys

    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known
    path -- module search path; path[0] is the script directory, else ''
    modules -- dictionary of loaded modules

    displayhook -- called to show results in an interactive session
    excepthook -- called to handle any uncaught exception other than SystemExit
      To customize printing in an interactive session or to install a custom
      top-level exception handler, assign other functions to replace these.

    stdin -- standard input file object; used by input()
    stdout -- standard output file object; used by print()
    stderr -- standard error object; used for error messages
      By assigning other file objects (or objects that behave like files)
      to these, it is possible to redirect all of the interpreter's I/O.

    last_type -- type of last uncaught exception
    last_value -- value of last uncaught exception
    last_traceback -- traceback of last uncaught exception
      These three are only available in an interactive session after a
      traceback has been printed.

    Static objects:

    builtin_module_names -- tuple of module names built into this interpreter
    copyright -- copyright notice pertaining to this interpreter
    exec_prefix -- prefix used to find the machine-specific Python library
    executable -- absolute path of the executable binary of the Python interpreter
    float_info -- a named tuple with information about the float implementation.
    float_repr_style -- string indicating the style of repr() output for floats
    hash_info -- a named tuple with information about the hash algorithm.
    hexversion -- version information encoded as a single integer
    implementation -- Python implementation information.
    int_info -- a named tuple with information about the int implementation.
    maxsize -- the largest supported length of containers.
    maxunicode -- the value of the largest Unicode code point
    platform -- platform identifier
    prefix -- prefix used to find the Python library
    thread_info -- a named tuple with information about the thread implementation.
    version -- the version of this interpreter as a string
    version_info -- version information as a named tuple
    __stdin__ -- the original stdin; don't touch!
    __stdout__ -- the original stdout; don't touch!
    __stderr__ -- the original stderr; don't touch!
    __displayhook__ -- the original displayhook; don't touch!
    __excepthook__ -- the original excepthook; don't touch!

    Functions:

    displayhook() -- print an object to the screen, and save it in builtins._
    excepthook() -- print an exception and its traceback to sys.stderr
    exc_info() -- return thread-safe information about the current exception
    exit() -- exit the interpreter by raising SystemExit
    getdlopenflags() -- returns flags to be used for dlopen() calls
    getprofile() -- get the global profiling function
    getrefcount() -- return the reference count for an object (plus one :-)
    getrecursionlimit() -- return the max recursion depth for the interpreter
    getsizeof() -- return the size of an object in bytes
    gettrace() -- get the global debug tracing function
    setdlopenflags() -- set the flags to be used for dlopen() calls
    setprofile() -- set the global profiling function
    setrecursionlimit() -- set the max recursion depth for the interpreter
    settrace() -- set the global debug tracing function

FUNCTIONS
    __breakpointhook__ = breakpointhook(...)
        breakpointhook(*args, **kws)

        This hook function is called by built-in breakpoint().

    __displayhook__ = displayhook(object, /)
        Print an object to sys.stdout and also save it in builtins._

    __excepthook__ = excepthook(exctype, value, traceback, /)
        Handle an exception by displaying it with a traceback on sys.stderr.

    __unraisablehook__ = unraisablehook(unraisable, /)
        Handle an unraisable exception.

        The unraisable argument has the following attributes:

        * exc_type: Exception type.
        * exc_value: Exception value, can be None.
        * exc_traceback: Exception traceback, can be None.
        * err_msg: Error message, can be None.
        * object: Object causing the exception, can be None.

    addaudithook(hook)
        Adds a new audit hook callback.

    audit(...)
        audit(event, *args)

        Passes the event to any audit hooks that are attached.

    call_tracing(func, args, /)
        Call func(*args), while tracing is enabled.

        The tracing state is saved, and restored afterwards.  This is intended
        to be called from a debugger from a checkpoint, to recursively debug
        some other code.

    exc_info()
        Return current exception information: (type, value, traceback).

        Return information about the most recent exception caught by an except
        clause in the current stack frame or in an older stack frame.

    exit(status=None, /)
        Exit the interpreter by raising SystemExit(status).

        If the status is omitted or None, it defaults to zero (i.e., success).
        If the status is an integer, it will be used as the system exit status.
        If it is another kind of object, it will be printed and the system
        exit status will be one (i.e., failure).

    get_asyncgen_hooks()
        Return the installed asynchronous generators hooks.

        This returns a namedtuple of the form (firstiter, finalizer).

    get_coroutine_origin_tracking_depth()
        Check status of origin tracking for coroutine objects in this thread.

    getallocatedblocks()
        Return the number of memory blocks currently allocated.

    getdefaultencoding()
        Return the current default encoding used by the Unicode implementation.

    getdlopenflags()
        Return the current value of the flags that are used for dlopen calls.

        The flag constants are defined in the os module.

    getfilesystemencodeerrors()
        Return the error mode used Unicode to OS filename conversion.

    getfilesystemencoding()
        Return the encoding used to convert Unicode filenames to OS filenames.

    getprofile()
        Return the profiling function set with sys.setprofile.

        See the profiler chapter in the library manual.

    getrecursionlimit()
        Return the current value of the recursion limit.

        The recursion limit is the maximum depth of the Python interpreter
        stack.  This limit prevents infinite recursion from causing an overflow
        of the C stack and crashing Python.

    getrefcount(object, /)
        Return the reference count of object.

        The count returned is generally one higher than you might expect,
        because it includes the (temporary) reference as an argument to
        getrefcount().

    getsizeof(...)
        getsizeof(object [, default]) -> int

        Return the size of object in bytes.

    getswitchinterval()
        Return the current thread switch interval; see sys.setswitchinterval().

    gettrace()
        Return the global debug tracing function set with sys.settrace.

        See the debugger chapter in the library manual.

    intern(string, /)
        ``Intern'' the given string.

        This enters the string in the (global) table of interned strings whose
        purpose is to speed up dictionary lookups. Return the string itself or
        the previously interned string object with the same value.

    is_finalizing()
        Return True if Python is exiting.

    set_asyncgen_hooks(...)
        set_asyncgen_hooks(* [, firstiter] [, finalizer])

        Set a finalizer for async generators objects.

    set_coroutine_origin_tracking_depth(depth)
        Enable or disable origin tracking for coroutine objects in this thread.

        Coroutine objects will track 'depth' frames of traceback information
        about where they came from, available in their cr_origin attribute.

        Set a depth of 0 to disable.

    setdlopenflags(flags, /)
        Set the flags used by the interpreter for dlopen calls.

        This is used, for example, when the interpreter loads extension
        modules. Among other things, this will enable a lazy resolving of
        symbols when importing a module, if called as sys.setdlopenflags(0).
        To share symbols across extension modules, call as
        sys.setdlopenflags(os.RTLD_GLOBAL).  Symbolic names for the flag
        modules can be found in the os module (RTLD_xxx constants, e.g.
        os.RTLD_LAZY).

    setprofile(...)
        setprofile(function)

        Set the profiling function.  It will be called on each function call
        and return.  See the profiler chapter in the library manual.

    setrecursionlimit(limit, /)
        Set the maximum depth of the Python interpreter stack to n.

        This limit prevents infinite recursion from causing an overflow of the C
        stack and crashing Python.  The highest possible limit is platform-
        dependent.

    setswitchinterval(interval, /)
        Set the ideal thread switching delay inside the Python interpreter.

        The actual frequency of switching threads can be lower if the
        interpreter executes long sequences of uninterruptible code
        (this is implementation-specific and workload-dependent).

        The parameter must represent the desired switching delay in seconds
        A typical value is 0.005 (5 milliseconds).

    settrace(...)
        settrace(function)

        Set the global debug tracing function.  It will be called on each
        function call.  See the debugger chapter in the library manual.

    unraisablehook(unraisable, /)
        Handle an unraisable exception.

        The unraisable argument has the following attributes:

        * exc_type: Exception type.
        * exc_value: Exception value, can be None.
        * exc_traceback: Exception traceback, can be None.
        * err_msg: Error message, can be None.
        * object: Object causing the exception, can be None.

DATA
    __stderr__ = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf...
    __stdin__ = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8...
    __stdout__ = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf...
    abiflags = ''
    api_version = 1013
    argv = ['/home/jfasch/venv/jfasch-home/lib64/python3.9/site-packages/i...
    base_exec_prefix = '/usr'
    base_prefix = '/usr'
    builtin_module_names = ('_abc', '_ast', '_codecs', '_collections', '_f...
    byteorder = 'little'
    copyright = 'Copyright (c) 2001-2022 Python Software Foundati...ematis...
    displayhook = <ipykernel.displayhook.ZMQShellDisplayHook object>
    dont_write_bytecode = False
    exec_prefix = '/home/jfasch/venv/jfasch-home'
    executable = '/home/jfasch/venv/jfasch-home/bin/python'
    flags = sys.flags(debug=0, inspect=0, interactive=0, opt...ation=1, is...
    float_info = sys.float_info(max=1.7976931348623157e+308, max_...epsilo...
    float_repr_style = 'short'
    hash_info = sys.hash_info(width=64, modulus=2305843009213693...iphash2...
    hexversion = 50924272
    implementation = namespace(name='cpython', cache_tag='cpython-39'...xv...
    int_info = sys.int_info(bits_per_digit=30, sizeof_digit=4)
    last_value = AttributeError("'tuple' object has no attribute 'append'"...
    maxsize = 9223372036854775807
    maxunicode = 1114111
    meta_path = [<class '_frozen_importlib.BuiltinImporter'>, <class '_fro...
    modules = {'IPython': <module 'IPython' from '/home/jfasch/venv/jfasch...
    path = ['/home/jfasch/work/jfasch-home/trainings/log/detail/2022-03-15...
    path_hooks = [<class 'zipimport.zipimporter'>, <function FileFinder.pa...
    path_importer_cache = {'/home/jfasch/.ipython': FileFinder('/home/jfas...
    platform = 'linux'
    platlibdir = 'lib64'
    prefix = '/home/jfasch/venv/jfasch-home'
    ps1 = 'In : '
    ps2 = '...: '
    ps3 = 'Out: '
    pycache_prefix = None
    stderr = <ipykernel.iostream.OutStream object>
    stdin = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>
    stdout = <ipykernel.iostream.OutStream object>
    thread_info = sys.thread_info(name='pthread', lock='semaphore', versio...
    version = '3.9.10 (main, Jan 17 2022, 00:00:00) \n[GCC 11.2.1 20210728...
    version_info = sys.version_info(major=3, minor=9, micro=10, releaselev...
    warnoptions = []

FILE
    (built-in)


[31]:
def eine_komplizierte_funktion(a, b):
    '''das ist eine sehr komplizierte funktion,
    die aber im endeffekt nix anderes macht, als a und b zusammenzuzaehlen
    und das ergebnis als wert hat.
    (sie tarnt sich also durch vergebliche komplexitaet)'''
    return a+b
[32]:
type(eine_komplizierte_funktion)
[32]:
function
[33]:
eine_komplizierte_funktion.__doc__
[33]:
'das ist eine sehr komplizierte funktion,\n    die aber im endeffekt nix anderes macht, als a und b zusammenzuzaehlen\n    und das ergebnis als wert hat.\n    (sie tarnt sich also durch vergebliche komplexitaet)'
[34]:
help(eine_komplizierte_funktion)
Help on function eine_komplizierte_funktion in module __main__:

eine_komplizierte_funktion(a, b)
    das ist eine sehr komplizierte funktion,
    die aber im endeffekt nix anderes macht, als a und b zusammenzuzaehlen
    und das ergebnis als wert hat.
    (sie tarnt sich also durch vergebliche komplexitaet)

Sequentielle vs. Konstante Suchzeit

[35]:
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[36]:
2 in l
[36]:
True
[37]:
12 in l
[37]:
True
[38]:
666 in l
[38]:
False
[39]:
s = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
[40]:
2 in s
[40]:
True
[42]:
12 in s
[42]:
True
[44]:
666 in s
[44]:
False

Exceptions

[46]:
zahl_als_string = '666'
zahl = int(zahl_als_string)
zahl
[46]:
666
[48]:
try:
    zahl_als_string = 'bledsinn'
    int(zahl_als_string)
except ValueError as e:
    print(e, type(e))
invalid literal for int() with base 10: 'bledsinn' <class 'ValueError'>

for vs. while, range()

[54]:
import random

n_tries = 1
while n_tries <= 6:
        eyes = random.randrange(1,7)
        if eyes == 6:
            print('hooray')
            break
        n_tries += 1
else:
        print('lose!')
hooray
[83]:
for try_no in range(1,7):
    eyes = random.randrange(1,7)
    if eyes == 6:
        print('hooray!')
        break
else:
    print('lose!')
lose!

String Methods (some)

[84]:
line = '       '
[88]:
len(line) == 0
[88]:
False
[89]:
line.isspace()
[89]:
True
[91]:
line = ' \r \t  \n'
line.isspace()
[91]:
True
[92]:
line = '       abc       '
line.strip()
[92]:
'abc'
[104]:
line = 'blahblahblah\n'
line.strip()
[104]:
'blahblahblah'
[106]:
line = '   blahblahblah   \t\t\r   \n'
line.strip()
[106]:
'blahblahblah'
[108]:
line = '\t    \r \t\n'
line.isspace()
[108]:
True
[111]:
line = line.strip()
len(line)
[111]:
0
[99]:
line = '       abc       '
line.rstrip()
[99]:
'       abc'
[100]:
line = '   abc\r\t\n'
line.rstrip()
[100]:
'   abc'
[101]:
line.rstrip('\n')
[101]:
'   abc\r\t'
[102]:
line.rstrip('\n\t')
[102]:
'   abc\r'
[103]:
line = 'cxyxyyyyxy'
line.rstrip('xy')
[103]:
'c'
[95]:
line = '     # comment '
line.find('#')
[95]:
5
[97]:
line[:5]
[97]:
'     '
[98]:
line[:line.find('#')]
[98]:
'     '

eval()

[116]:
table_str = '{"eins": 1, "zwei": 2}'
type(table_str)
[116]:
str
[117]:
try:
    table_str["eins"]
except Exception as e:
    print(type(e), e)
<class 'TypeError'> string indices must be integers
[118]:
table_str[0]
[118]:
'{'
[120]:
table_dict = eval(table_str)
type(table_dict)
[120]:
dict
[122]:
table_dict["eins"]
[122]:
1
[123]:
table_dict["drei"] = 3
[124]:
table_dict["drei"]
[124]:
3
[126]:
table_str
[126]:
'{"eins": 1, "zwei": 2}'
[128]:
id(table_str)
[128]:
139769175732912
[129]:
id(table_dict)
[129]:
139769175738624

Geht auch fuer andere Datentypen!!

[130]:
satan_str = '666'
[132]:
satan_int = eval(satan_str)
[134]:
satan_int
[134]:
666
[136]:
try:
    eval('if True: print("hallo")')
except Exception as e:
    print(type(e), e)
<class 'SyntaxError'> invalid syntax (<string>, line 1)
[137]:
result_of_print = print('hallo')
hallo
[140]:
print(result_of_print)
None
[143]:
result_of_evald_print = eval('print("hallo")')
hallo
[144]:
print(result_of_evald_print)
None

exec()

[145]:
code_str = """
for i in range(5):
    print(i)
"""
[147]:
type(code_str)
[147]:
str
[149]:
exec(code_str)
0
1
2
3
4
[155]:
compiled_code = compile(code_str, mode='exec', filename='woswasi.py')
[156]:
type(compiled_code)
[156]:
code
[158]:
exec(code)
0
1
2
3
4
[159]:
if True: print(5)
5
[161]:
7
[161]:
7
[162]:
code
[162]:
<code object <module> at 0x7f1e91eb42f0, file "woswasi.py", line 2>

Iterator protocol

[165]:
r = range(3)
type(r)
[165]:
range
[167]:
it = iter(r)
type(it)
[167]:
range_iterator
[168]:
next(it)
[168]:
0
[169]:
next(it)
[169]:
1
[170]:
next(it)
[170]:
2
[172]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
<class 'StopIteration'>
[173]:
for i in range(3):
    print(i)
0
1
2
[174]:
for elem in ['caro', 'joerg', 'johanna', 'philipp']:
    print(elem)
caro
joerg
johanna
philipp
[175]:
i = 0
for elem in ['caro', 'joerg', 'johanna', 'philipp']:
    print(i, elem)
    i += 1
0 caro
1 joerg
2 johanna
3 philipp
[176]:
for elem in enumerate(['caro', 'joerg', 'johanna', 'philipp']):
    print(elem)
(0, 'caro')
(1, 'joerg')
(2, 'johanna')
(3, 'philipp')
[179]:
for i, elem in enumerate(['caro', 'joerg', 'johanna', 'philipp']):
    print(i, elem)
0 caro
1 joerg
2 johanna
3 philipp

Dictionary Iteration

[180]:
user = {
    'ID': 1,
    'Firstname': 'Joerg',
    'Lastname': 'Faschingbauer',
    'Birth': '19.06.1966',
}
[182]:
for k in user:
    print(k)
ID
Firstname
Lastname
Birth
[184]:
for k in user.keys():
    print(k)
ID
Firstname
Lastname
Birth
[186]:
for v in user.values():
    print(v)
1
Joerg
Faschingbauer
19.06.1966
[188]:
for elem in user.items():
    print(elem)
('ID', 1)
('Firstname', 'Joerg')
('Lastname', 'Faschingbauer')
('Birth', '19.06.1966')
[189]:
for elem in user.items():
    k = elem[0]
    v = elem[1]
    print('key:', k, ', value:', v)
key: ID , value: 1
key: Firstname , value: Joerg
key: Lastname , value: Faschingbauer
key: Birth , value: 19.06.1966
[190]:
for k, v in user.items():
    print('key:', k, ', value:', v)
key: ID , value: 1
key: Firstname , value: Joerg
key: Lastname , value: Faschingbauer
key: Birth , value: 19.06.1966

Classes, Attributes, OO

[192]:
class User:
    pass
[194]:
type(User)
[194]:
type
[195]:
joerg = User()
[196]:
type(joerg)
[196]:
__main__.User

int is also callable

[197]:
i = int()
[198]:
i
[198]:
0
[199]:
joerg.id = 1
joerg.firstname = 'Jörg;DI'
joerg.lastnmae = 'Faschingbauer'
joerg.birth = '19.6.1966'
[201]:
joerg
[201]:
<__main__.User at 0x7f1e8c0fe2e0>
[202]:
joerg.firstname
[202]:
'Jörg;DI'

Types and Instances

[203]:
int
[203]:
int
[204]:
print(int)
<class 'int'>
[205]:
i = 666
[217]:
i
[217]:
666
[218]:
j = int()
j
[218]:
0
[236]:
j = int(666)
j
[236]:
666
[238]:
j = int('666')
j
[238]:
666
[226]:
j = 666
j
[226]:
666
[240]:
j = int('f', 16)
j
[240]:
15
[228]:
dir(j)
[228]:
['__abs__',
 '__add__',
 '__and__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__invert__',
 '__le__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 '__xor__',
 'as_integer_ratio',
 'bit_length',
 'conjugate',
 'denominator',
 'from_bytes',
 'imag',
 'numerator',
 'real',
 'to_bytes']
[230]:
j.__bool__()
[230]:
True
[231]:
bool(j)
[231]:
True
[223]:
hex(id(j))
[223]:
'0x7f1e8c0b3130'
[234]:
print(type(i))
<class 'int'>
[235]:
i.__class__
[235]:
int
[212]:
int_liste = []
int_liste.append(42)
int_liste.append(666)
int_liste
[212]:
[42, 666]
[213]:
class User:
    pass
[224]:
u = User()
print(u)
print(type(u))
<__main__.User object at 0x7f1e8c0fe340>
<class '__main__.User'>
[232]:
dir(u)
[232]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']
[241]:
print(u.__class__)
<class '__main__.User'>
[242]:
class User:
    def __init__(self, uid):
        pass
[244]:
try:
    u = User()
except Exception as e:
    print(type(e), e)
<class 'TypeError'> __init__() missing 1 required positional argument: 'userid'
[246]:
satan = User(666)
print(satan)
<__main__.User object at 0x7f1e8c0fe760>
[248]:
try:
    satan.uid
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'User' object has no attribute 'id'
[251]:
class User:
    def __init__(self, uid):
        self.uid = uid
[252]:
u = User(42)
u.uid
[252]:
42
[253]:
u = User(0)
u.uid
[253]:
0
[254]:
u = User(-666)
u.uid
[254]:
-666
[255]:
class User:
    def __init__(self, uid):
        assert uid > 0
        self.uid = uid
[257]:
try:
    u = User(0)
except Exception as e:
    print(type(e), e)
<class 'AssertionError'>
[258]:
u1 = User(1)
u2 = User(1)

Metaprogramming? Types? What is a Type?

[259]:
u = User(42)
print(type(u))
<class '__main__.User'>
[260]:
type_of_user = u.__class__
print(type_of_user)
<class '__main__.User'>
[264]:
print(type(type_of_user))
<class 'type'>
[266]:
dir(type_of_user)
[266]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']
[267]:
class User:
    def __init__(self, uid, firstname, lastname, birth):
        assert uid > 0
        self.uid = uid
        self.firstname = firstname
        self.lastname = lastname
        self.birth = birth
[269]:
print(type(User))
<class 'type'>
[272]:
def ctor(self, uid, firstname, lastname, birth):
    assert uid > 0
    self.uid = uid
    self.firstname = firstname
    self.lastname = lastname
    self.birth = birth
def blah(self):
    self.firstname = self.firstname[::-1]
    self.lastname = self.lastname[::-1]
[274]:
User = type('User', (), {'__init__': ctor, 'scramble': blah})
[276]:
type(User)
[276]:
type
[277]:
u = User(1, 'Hansjörg', 'Faschingbauer', '19.06.1966')
[279]:
u.uid
[279]:
1
[280]:
u.scramble()
[281]:
u.firstname
[281]:
'gröjsnaH'
[282]:
u.scramble()
u.firstname
[282]:
'Hansjörg'

Is the same as (recommended):

[283]:
class User:
    def __init__(self, uid, firstname, lastname, birth):
        assert uid > 0
        self.uid = uid
        self.firstname = firstname
        self.lastname = lastname
        self.birth = birth
    def scramble(self):
        self.firstname = self.firstname[::-1]
        self.lastname = self.lastname[::-1]

Another way to dynamically create types: exec()

[285]:
class_str = '''
class User:
    def __init__(self, uid, firstname, lastname, birth):
        assert uid > 0
        self.uid = uid
        self.firstname = firstname
        self.lastname = lastname
        self.birth = birth
    def scramble(self):
        self.firstname = self.firstname[::-1]
        self.lastname = self.lastname[::-1]
'''
[286]:
context = {}
exec(class_str, context)
[287]:
print(context['User'])
<class 'User'>

OO Everywhere

[299]:
s = 'hallo'
[301]:
type(s)
[301]:
str
[303]:
s.find('ll')
[303]:
2
[304]:
d = {
    1: User(1, 'Joerg', 'Faschingbauer', '19.6.1966'),
    2: User(2, 'Caro', 'Faschingbauer', '25.4.1997'),
    }
[305]:
type(d)
[305]:
dict
[306]:
d[1]
[306]:
<__main__.User at 0x7f1e8c1c2e50>
[308]:
d.get(1)
[308]:
<__main__.User at 0x7f1e8c1c2e50>
[309]:
d['joleckmi'] = ['jo', 'oida', 666]

Dictionary Operations

[310]:
d = {
    '19.6.1966': 2,
    '1.1.1900': 1
}
[317]:
counter = d.get('19.6.1966')
print(counter)
2
[318]:
d['19.6.1966'] = counter + 1
[314]:
counter = d.get('25.4.1997')
print(counter)
None
[316]:
try:
    d['25.4.1997']
except Exception as e:
    print(type(e), e)
<class 'KeyError'> '25.4.1997'

collections.defaultdict

[319]:
from collections import defaultdict
[320]:
counters = defaultdict(int)
[321]:
int()
[321]:
0
[322]:
counters['19.6.1966']
[322]:
0
[323]:
counters['1.1.1900'] += 1
[324]:
counters['1.1.1900']
[324]:
1