Python例子小结

Control Structures

Boolean Logic

1
2
3
1 == 1 and 2 == 2
1 == 2 or 2 == 2
not 1 > 7
1
2
3
True
True
False

Operator Precedence

List

1
2
3
4
5
number = 3
things = ["string", 0, [1, 2, number], 4.56]
print(things[1])
print(things[2])
print(things[2][3])
1
2
3
0
[1, 2, 3]
3

Functions

函数可以直接调用!

1
2
3
4
5
6
7
8
def add(x,y):
return x+y # return can't use out of functions
def do_twice(func, x, y):
return func(func(x,y), func(x,y))
# functions can use as arguments
a = 5
b = 10
print(do_twice(add, a, b))
1
2
3
>>>
30
>>>

Exceptions

ImportError : an import fails;
IndexError : a list is indexed with an out-of-range number;
NameError : an unknown variable is used;
SyntaxError : the code can’t be parsed propertly;
TypeError : a function is called on a value of an inappropriate value.

Exception Handing

1
2
3
4
5
try:
world = 'spam'
print(world/0)
except:
print('An error ocurred')
1
2
3
>>>
An error ocurred
>>>

OR

1
2
3
4
5
print(1)
assert 2+2 == 4 # a sanity-check,turn on or turn off
print(2)
assert 1+1 == 3
print(3)
1
2
3
4
5
>>>
1
2
AssertError
>>>
1
2
temp = -10
assert(temp >=10), "Colder than absolute zero!"
1
2
3
>>>
AssertError: Colder than absolute zero!"
>>>

Functional Programming

Lambda

lambad 三种用法:

1
2
3
4
#named funciton
def polynomial(x):
return x**2 + 5*x + 4
print(polynomial(-4)
1
2
#lambda
print((lambad x: x**2 + 5*x + 4) (-4))
1
2
double = lambda x: x**2 + 5*x + 4
print(double(-4))
1
>>> 0

map

The function map takes a function and an iterable as arguments, and returns a new iterable with the function applied to each argument.

1
2
3
4
5
def add_five(x):
return x + 5
nums = [11, 22, 33, 44, 55]
result = list(map(add_five, nums))
print(result)
1
>>> [16, 27, 38, 49, 60]

Filter

The function filter filters an iterable by removig iterms that don’t match a predicate

1
2
nums = [11, 22, 33, 44, 55]
res = lis(filter(lambda x: x%2==0, nums))
1
>>> [22, 44]]

generators(yield)

Generators ate a type of iterable, like lists or tuples.

They can be created using functions and the yield statement.

Using generatoers results in improved performance, which is the result of the lazy (on demand) generation of values, which translates to lower memory usage.

1
2
3
4
5
6
7
def countdown():
i = 5
while i > 0:
yield i
i -= 1
for i in countdown():
print(i)
1
2
3
4
5
6
>>>
5
4
3
2
1
1
2
3
4
5
def numbers(x):
for i in range(x) :
if i % 2 ==0:
yield i
print(list(numbers(11)))
1
>>> [0,2,4,6,8,10]

Decorators( @ )

装饰函数个人理解,相当于定义一个嵌套函数,作为主函数,@后面加拓展函数,调用只需拓展函数名即可。

Thisideal when you need to extend the functionality of functionality of functions that you don’t want to modify.

原理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def decor(func):
def wrap():
print('=======')
func()
print('=======')
return wrap
def print_text():
print('Hello world')
decorated = decor(print_taxt)
decorated()
/*
def decor(func):
print('========')
func()
print('========')
def print_text():
print('Hello world')
decorated = decor(print_text)
*/

Using @ (decorate):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def decor(func):
def wrap():
print('========')
func()
print('========')
@decor
def print_text():
print('Hello world')
print_text()
/*
def decor(func):
print('========')
func()
print('========')
@decor
def print_text():
print('Hello world')
print_text

result:

1
2
3
========
Hello world
========

Object-Oriented Programming (OOP)

Class

The class describes what the object will be, but is separate from the object itself .

You can use the same class as a buleprint for creating multiple different objects.

开头字母大写!This is a good hobby!

1
2
3
4
5
class Cat:
def __init(self, color, legs): #__init__表示函数名取函数自身
self.color = color
self.legs = legs
felix = Cat('ginger', 4) #object的属性

init : This is called when an instance (object) of the class is created , using the class name as a function.

Methods

All methods must have self as their first parameter

1
2
3
4
5
6
7
8
9
10
class Dog:
def __init__(self, name, color):
self.name = name
self.color = color
/*def bark(self):
print('Woof!')*/
fido = Dog('Fido', 'brown')
print(fido.name)
fido.bark()
1
2
>>> Fido
>>> Woof!

Class attributes

This is applies whrn you call an undefined

1
2
3
4
5
6
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
rect = Rectangle(7,8)
print(rect.color)
1
AttributeError: 'Rectangle' object has no attribute 'color'

声明:

欢迎转载,转载时请注明出处
JacobYRJ