0
Functions
Functions are declared with the “def” keyword. Optional arguments are set in the function declaration after the mandatory arguments by being assigned a default value. For named arguments, the name of the argument is assigned a value. Functions can return a tuple (and using tuple unpacking you can effectively return multiple values). Lambda functions are ad hoc functions that are comprised of a single statement. Parameters are passed by reference, but immutable types (tuples, ints, strings, etc) cannot be changed. This is because only the memory location of the item is passed, and binding another object to a variable discards the old one, so immutable types are replaced. For example:
26.
Same as def f(x): return x + 1
functionvar = lambda x: x + 1
>>> print functionvar(1)
2
27.
an_int and a_string are optional, they have default values
28.
if one is not passed (2 and "A default string", respectively).
def passing_example(a_list, an_int=2, a_string="A default string"):
a_list. append("A new item")
an_int = 4
return a_list, an_int, a_string
>>> my_list = [1, 2, 3]
>>> my_int = 10
>>> print passing_example(my_list, my_int)
([1, 2, 3, 'A new item'], 4, "A default string")
>>> my_list
[1, 2, 3, 'A new item']
>>> my_int
10
Classes
Python supports a limited form of multiple inheritance in classes. Private variables and methods can be declared (by convention, this is not enforced by the language) by adding at least two leading underscores and at most one trailing one (e.g. “__spam”). We can also bind arbitrary names to class instances. An example follows:
class MyClass:
common = 10
def __init__(self):
self. myvariable = 3
def myfunction(self, arg1, arg2):
return self. myvariable
# This is the class instantiation
>>> classinstance = MyClass()
>>> classinstance. myfunction(1, 2)
3
29.
This variable is shared by all classes.
>>> classinstance2 = MyClass()
>>> classinstance. common
10
>>> classinstance2.common
10
30.
Note how we use the class name
31.
instead of the instance.
>>> MyClass. common = 30
>>> classinstance. common
30
>>> classinstance2.common
30
32.
This will not update the variable on the class,
33.
instead it will bind a new object to the old
34.
variable name.
>>> classinstance. common = 10
>>> classinstance. common
10
>>> classinstance2.common
30
>>> MyClass. common = 50
35.
This has not changed, because "common" is
36.
now an instance variable.
>>> classinstance. common
10
>>> classinstance2.common
50
37.
This class inherits from MyClass. Multiple
38.
inheritance is declared as:
39.
class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
# The "self" argument is passed automatically
# and refers to the class instance, so you can set
# instance variables as above, but from inside the class.
def __init__(self, arg1):
self. myvariable = 3
print arg1
>>> classinstance = OtherClass("hello")
hello
>>> classinstance. myfunction(1, 2)
3
40.
This class doesn't have a .test member, but
41.
we can add one to the instance anyway. Note
42.
that this will only be a member of classinstance.
>>> classinstance. test = 10
>>> classinstance. test
10
Exceptions
Exceptions in Python are handled with try-except [exceptionname] blocks:
def some_function():
try:
# Division by zero raises an exception
10 / 0
except ZeroDivisionError:
print "Oops, invalid."
else:
# Exception didn't occur, we're good.
pass
finally:
# This is executed after the code block is run
# and all exceptions have been handled, even
# if a new exception is raised while handling.
print "We're done with that."
>>> some_function()
Oops, invalid.
We're done with that.
Importing
External libraries are used with the import [libname] keyword. You can also use from [libname] import [funcname] for individual functions. Here is an example:
import random
from time import clock
randomint = random. randint(1, 100)
>>> print randomint
64
File I/O
Python has a wide array of libraries built in. As an example, here is how serializing (converting data structures to strings using the pickle library) with file I/O is used:
import pickle
mylist = ["This", "is", 4, 13327]
43.
Open the file C:binary.dat for writing. The letter r before the
44.
filename string is used to prevent backslash escaping.
myfile = file(r"C:binary.dat", "w")
pickle. dump(mylist, myfile)
myfile. close()
myfile = file(r"C:text.txt", "w")
myfile. write("This is a sample string")
myfile. close()
myfile = file(r"C:text.txt")
>>> print myfile. read()
'This is a sample string'
myfile. close()
45.
Open the file for reading.
myfile = file(r"C:binary.dat")
loadedlist = pickle. load(myfile)
myfile. close()
>>> print loadedlist
['This', 'is', 4, 13327]
Miscellaneous
* Conditions can be chained. 1 < a < 3 checks that a is both less than 3 and more than 1.
* You can use del to delete variables or items in arrays.
* List comprehensions provide a powerful way to create and manipulate lists. They consist of an expression followed by a for clause followed by zero or more if or for clauses, like so:
>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]
46.
Check if an item has a specific property.
47.
"any" returns true if any item in the list is true.
>>> any([i % 3 for i in [3, 3, 4, 4, 3]])
True
48.
This is because 4 % 3 = 1, and 1 is true, so any()
49.
returns True.
50.
Check how many items have this property.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)
2
>>> del lst1[0]
>>> print lst1
[2, 3]
>>> del lst1
* Global variables are declared outside of functions and can be read without any special declarations, but if you want to write to them you must declare them at the beginning of the function with the “global” keyword, otherwise Python will bind that object to a new local variable (be careful of that, it’s a small catch that can get you if you don’t know it). For example:
number = 5
def myfunc():
# This will print 5.
print number
def anotherfunc():
# This raises an exception because the variable has not
# been bound before printing. Python knows that it an
# object will be bound to it later and creates a new, local
# object instead of accessing the global one.
print number
number = 3
def yetanotherfunc():
global number
# This will correctly change the global.
number = 3
Tümünü Göster