Wednesday

python functions generators closures decorators



Types of arguments:



#default values:


def sub1( a,b='default',i=0)

named arguments


def info(spacing=15, object=odbchelper):

tuple (args,params)


def sumsq2(*a): return sum(x*x for x in a)

dictionary


def sumsq2(**a):



generators in python - used yield insted of return


def fibonacci()
i=j=1
while True:
r,i,j = i,j,i+j
yield r


for rabbits in fibonacci():
print rabbits
if rabbit > 100 : break
>>
1 1 2 3 5 8 13 21 34 55 89 144

Closures


def makeAdder(addend):
def adder(augend):
return audend + addend
return adder


a23=MakeAdder(23)
a42=MakeAdder(42)

print a23(100) , a42(100) , a23(a42(100))
>> 123 142 165


decorators



@<decor>
def <name>
#is like
def (name)
name = <decor>(<name>)


#or another example
@dec2
@dec1
def func(arg1, arg2, ...):
pass

#This is equivalent to:

def func(arg1, arg2, ...):
pass
func = dec2(dec1(func))

and singleton example


def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance

@singleton
class MyClass:
...


more...

No comments:

test smtp server with powershell

Send-MailMessage -SMTPServer smtp.domain.com -To [email protected] -From [email protected] -Subject "This is a test email" -Body ...