python:power(a,b)、list.Slice、list.reverse、try-except、object-oriented programming (OOP)
>>> 2**10
1024
equal to math.power(2, 10) Slicing syntax: L[start:stop:stride]
All slicing parameters are optional:
>>>
>>> L
['red', 'blue', 'green', 'black', 'white']
>>> L[3:]
['black', 'white']
>>> L[:3]
['red', 'blue', 'green']
>>> L[::2]
['red', 'green', 'white']
Reverse:
>>>
>>> r = L[::-1]
>>> r
['white', 'black', 'green', 'blue', 'red']
>>> r2 = list(L)
>>> r2
['red', 'blue', 'green', 'black', 'white']
>>> r2.reverse() # in-place
>>> r2
['white', 'black', 'green', 'blue', 'red']
def print_sorted(collection):
....: try:
....: collection.sort()
....: except AttributeError:
....: pass
....: print(collection)
def filter_name(name):
....: try:
....: name = name.encode('ascii')
....: except UnicodeError, e:
....: if name == 'Gaël':
....: print('OK, Gaël')
....: else:
....: raise e
....: return name
>>> class Student(object):
... def __init__(self, name):
... self.name = name
... def set_age(self, age):
... self.age = age
... def set_major(self, major):
... self.major = major
...
>>> anna = Student('anna')
In the previous example, the Student class has __init__, set_age and set_majormethods. Its attributes are name, age and major. We can call these methods and attributes with the following notation: classinstance.method or classinstance.attribute. The __init__ constructor is a special method we call with: MyClass(init parameters ifany).
Now, suppose we want to create a new class MasterStudent with the same methods and attributes as the previous one, but with an additional internship attribute. We won’t copy the previous class, but inherit from it:
>>> class MasterStudent(Student):
... internship = 'mandatory, from March to June'
...
>>> james = MasterStudent('james')
>>> james.internship
'mandatory, from March to June'
>>> james.set_age(23)
>>> james.age
23
The MasterStudent class inherited from the Student attributes and methods.
Thanks to classes and object-oriented programming, we can organize code with different classes corresponding to different objects we encounter (an Experiment class, an Image class, a Flow class, etc.), with their own methods and attributes. Then we can use inheritance to consider variations around a base class and re-use code. Ex : from a Flow base class, we can create derived StokesFlow, TurbulentFlow, PotentialFlow, etc.