Lecture#3
.pdfHigh performance computing for non-programmers
Glib Ivashkevych
junior researcher, NSC KIPT
Lecture #3:
Python programming language: Overview
Functions default arguments
def my_func(a, b=None):
print a print b
my_func(1) #the same as my_func(1, None) my_func(1, 2)
Functions calls
def my_func(a, b=None):
print a print b
my_func(b=2, a=1) my_func(b=2, 1) #SyntaxError
l = [1,2]; my_func(*l) #Unpacking
d = {‘a’:1, ‘b’:2}; my_func(**d) #Unpacking
Functions
variable number of args
def func(a, *args):
print a print args
func(1) func(1, 2, 3) func(1, *(2,3))
func(1, *[2,3]); func(1, [2,3]) #Not the same!
Functions altogether
def func(a, *args, **kwargs):
print a
print args print kwargs
func(1, 2, 3, name=’name’) func(1, *[2,3], **{‘name’:’name’})
func(1, **{‘name’:’name’}, *[2,3]) #SyntaxError
Functions tricky stuff
functions are objects
created when def is encountered we can:
add attributes to functions assign them
return them
names in functions are local, except when global instruction is used
Classes
classes are objects too (oh, man!) created when class is encountered
class Primitive(object): pass
we can create classes at runtime
Classes
constructors & attributes
class Primitive(object): def __init__(self):
pass
class Primitive(object):
field = 5. #class attribute?
def __init__(self, num): self.field = num #Nope!
Classes
constructors & attributes
class Primitive(object):
field = 5. #class attribute?
def __init__(self, num): Primitive.field = num #Yeap!
x = Primitive(1) #is the same as x = Primitive.__new__(Primitive, 1)
Classes methods
class Primitive(object): field = 5.
def get_field(self): return self.field
x = Primitive() f = x.get_field()