目录
- PYTHON3 OUTLINE
PYTHON3 OUTLINE
本文PYTHON3 OUTLINE是python3-in-one-pic的markdown版本。
import this
""" The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those! """
syntax rules
case sensitive
a = 1
A = 2
print(a is not A) # True
comments
# this line will not be interpreted
code blocks
- codes with same indentation are in same scope
- Use 4 spaces per indentation level
native datatypes
number
- integer
a = 1
b = 0x10 # 16
print(type(a)) # <class 'int'>
- float
c = 1.2
d = .5 # 0.5
g = .314e1 # 3.14
print(type(g)) # <class 'float'>
- complex
e = 1+2j
f = complex(1, 2)
print(type(e)) # <class 'complex'>
print(f == e) # True
- operators
## Operators: + - * / ** // %
print(1 + 1) # 2
print(2 - 2) # 0
print(3 * 3) # 9
print(5 / 4) # 1.25
print(2 ** 10) # 1024
print(5 // 4) # 1
print(5 % 4) # 1
- casting
- integer/string -> float
```python
print(float.__doc__)
""" float(x) -> floating point number
- integer/string -> float
Convert a string or number to a floating point number, if possible. """
print(float(3)) # 3.0
print(3 / 1) # 3.0
print(float("3.14")) # 3.14- float/string -> integer
python
print(int.__doc__)
"""int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
int('0b100', base=0)
4"""
print(int(3.14)) # 3
print(int("3", base = 10)) # 3
print(int("1010", base = 2)) # 10
print(int("0b1010", base = 0)) # 10
```
string
s1 = ':dog:\n'
s2 = "Dogge's home"
s3 = """ Hello, Dogge! """
print(type(s1)) # <class 'str'>
print("%s, %s, %s" % (s1, s2, s3))
""":dog:
, Dogge's home, Hello, Dogge!
"""
- length
print(len(s1)) # 6
- slicing
s = 'study and practice'
print('{0}:{1}'.format(s[:5], s[-8:])) # study:practice
- operator +
print("abc" + "." + "xyz") # "abc.xyz"
- casting
print(str.__doc__)
"""str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'."""
print(str(3.14)) # "3.14"
print(str(3)) # "3"
print(str([1,2,3])) # "[1,2,3]"
print(str((1,2,3))) # "(1,2,3)"
print(str({1,2,3})) # "{1,2,3}"
print(str({'python': '*.py', 'javascript': '*.js'})) # "{'python': '*.py', 'javascript': '*.js'}"
bytes
- list of ascii character
- 0-255/x00-xff
byt = b'abc'
print(type(byt)) # <class 'bytes'>
print(byt[0] == 'a')# False
print(byt[0] == 97) # True
- length
print(len(byt)) # 3
boolean
- True
- False
print(type(True)) # <class 'bool'>
None
print(None is None) # True
print(type(None)) # <class 'NoneType'>
list
l = ['python', 3, 'in', 'one']
print(type(l)) # <class 'list'>
- length
print(len(l)) # 4
- slicing
print(l[0]) # 'python'
print(l[-1]) # 'one'
print(l[1:-1]) # [3, 'in']
- alter
l.append('pic') # ['python', 3, 'in', 'one', 'pic']
l.insert(2, '.4.1') # ['python', 3, '.4.1', 'in', 'one', 'pic']
l.extend(['!', '!']) # ['python', 3, '.4.1', 'in', 'one', 'pic', '!', '!']
print(l.pop()) # '!' ['python', 3, '.4.1', 'in', 'one', 'pic', '!']
print(l.pop(2)) # '.4.1' ['python', 3, 'in', 'one', 'pic', '!']
l.remove("in") # ['python', 3, 'one', 'pic', '!']
del l[2] # ['python', 3, 'pic', '!']
- index
print(l.index('pic')) # 2
tuple
tp = (1, 2, 3, [4, 5])
print(type(tp)) # <class 'tuple'>
## Length
print(len(tp)) # 4
print(tp[2]) # 3
tp[3][1] = 6
print(tp) # (1, 2, 3, [4, 6])
## Single element
tp = (1, ) # 'tuple'
tp = (1) # 'int'
- immutable list
- assign multiple values
v = (3, 2, 'a')
(c, b, a) = v
print(a, b, c) # a 2 3
set
st = {'s', 'e', 'T'}
print(type(st)) # <class 'set'>
## Length
print(len(st)) # 3
## Empty
st = set()
print(len(st)) # 0
st = {}
print(type(st)) # <class 'dict'>
- alter
st = set(['s', 'e', 'T'])
st.add('t') # st == {'s', 'e', 't', 'T'}
st.add('t') # st == {'s', 'e', 't', 'T'}
st.update(['!', '!']) # st == {'s', 'e', 't', 'T', '!'}
st.discard('t') # st == {'T', '!', 's', 'e'} # No Error
st.remove('T') # st == {'s', 'e', '!'} # KeyError
st.pop() # 's' # st == {'e'}
st.clear() # st == set()
dict
dic = {}
print(type(dic)) # <class 'dict'>
dic = {'k1': 'v1', 'k2': 'v2'}
## Length
print(len(dic)) # 2
print(dic['k2']) # 'v2'
print(dic.get('k1')) # 'v1'
print(dic.get('k3', 'v0')) # 'v0'
dic['k2'] = 'v3'
print(dic) # {'k1': 'v1', 'k2': 'v3'}
print('k2' in dic) # True
print('v1' in dic) # False
float
Standard Libraries
Pythonic
Module
package
"""
MyModule/
|--SubModuleOne/
|--__init__.py
|--smo.py
# smo.py
def run():
print("Running MyModule.SubModuleOne.smo!")
"""
from MyModule.SubModule import smo
smo.run() # Running MyModule.SubModuleOne.smo!
search path
- current directory
- echo $PYTHONPATH
- sys.path
import
import os
print(os.name) # posix
from sys import version_info as ver
print("VERSON: {}.{}".format(ver.major, ver.minor)) # VERSON: 3.5
from math import *
print(pi) # 3.141592653589793
flow control
comprehensions
- dict
ls = {s: len(s) for s in ["Python", "Javascript", "Golang"]}
print(ls) # {'Python': 6, 'Javascript': 10, 'Golang': 6}
sl = {v: k for k, v in ls.items()}
print(sl) # {10: 'Javascript', 6: 'Golang'}
- set
s = {2 * x for x in range(10) if x ** 2 > 3}
print(s) # {4, 6, 8, 10, 12, 14, 16, 18}
pairs = set([(x, y) for x in range(2) for y in range(2)])
print(pairs) # {(0, 1), (1, 0), (0, 0), (1, 1)}
- list
pairs = [(x, y) for x in range(2) for y in range(2)]
print(pairs) # [(0, 0), (0, 1), (1, 0), (1, 1)]
s = [2 * x for x in range(10) if x ** 2 > 3]
print(s) #[4, 6, 8, 10, 12, 14, 16, 18]
loop
- iterators & generators
- generators: 在访问时产生,只产生一次
- iterators: 访问时返回下一个数据
```python
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index] # return a generator
nohtyp = reverse("Python")
print(nohtyp) # <generator object reverse at 0x1029539e8>
for i in nohtyp:
print(i) # n # o # h # t # y # P
python = iter("Python")
print(python) # <str_iterator object at 0x10293f8d0>
for i in python:
print(i) # P # y # t # h # o # n- break/continue
python
for n in range(2, 10):
if n % 2 == 0:
print("Found an even number ", n)
continue
if n > 5:
print("GT 5!")
break- while/for
python
prod = 1
i = 1
while i < 10:
prod = prod * i
i += 1
print(prod)
for i in "Hello":
print(i)
```
if
import sys
if sys.version_info.major < 3:
print("Version 2.X")
elif sys.version_info.major > 3:
print("Future")
else:
print("Version 3.X")
function
arguments
- decorator
def log(f):
def wrapper():
print("Hey log~")
f()
print("Bye log~")
return wrapper
@log
def fa():
print("This is fa!")
# Equal to...
def fb():
print("This is fb!")
fb = log(fb)
fa()
print("*"*10)
fb()
- lambda
# lambda arg: exp
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) "[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]"
pairs.sort(key=lambda pair: pair[0])
print(pairs) "[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]"
- arbitrary arguments
def f(*args, **kargs):
print("args ", args)
print("kargs ", kargs)
print("FP: {} & Scripts: {}".format(kargs.get("fp"), "/".join(args)))
f("Python", "Javascript", ms = "C++", fp = "Haskell")
# args ('Python', ‘Javascript’)
# kargs {'ms': 'C++', 'fp': 'Haskell'}
# FP: Haskell and Scripts: Python/Javascript
def f(*args, con = " & "):
print(isinstance(args, tuple))
print("Hello", con.join(args))
f("Python", "C", "C++", con = "/")
# True
# "Hello Python/C/C++"
- keyword arguments
def f(v, l = "Python"):
"""return '$v, $l'"""
return "{}, {}!".format(v, l)
print(f("Hello")) # "Hello, Python!"
print(f("Bye", "C/C++")) # "Bye, C/C++!"
- default arguments
def f(name = "World"):
"""return 'Hello, $name'"""
return "Hello, {}!".format(name)
print(f()) # 'Hello, World!'
print(f("Python")) # 'Hello, Python!'
definition
def f():
"""return 'Hello, World!'"""
return "Hello, World!"
print(f()) # "Hello, World!"
print(f.__doc__) # "return 'Hello, World!'"
class/OOP
override
class Animal:
"""This is an Animal"""
def __init__(self, can_fly = False):
self.can_fly = can_fly
def fly(self):
if self.can_fly:
print("I CAN fly!")
else:
print("I can not fly!")
class Bird(Animal):
"""This is a Bird"""
def fly(self):
print("I'm flying high!")
bird = Bird()
bird.fly() # I'm flying high!
inheritance
class Animal:
"""This is an Animal"""
def __init__(self, can_fly = False):
self.can_fly = can_fly
def fly(self):
if self.can_fly:
print("I CAN fly!")
else:
print("I can not fly!")
class Dog(Animal):
"""This is a Dog"""
def bark(self):
print("Woof!")
d = Dog()
d.fly() # I can not fly!
d.bark() # Woof!
instance
class Animal:
pass
class Human:
pass
a = Animal()
h = Human()
print(isinstance(a, Animal)) # True
print(isinstance(h, Animal)) # False
__init__ & self
class Animal:
"""This is an Animal"""
def __init__(self, can_fly = False):
print("Calling __init__() when instantiation!")
self.can_fly = can_fly
def fly(self):
if self.can_fly:
print("I CAN fly!")
else:
print("I can not fly!")
a = Animal() # Calling __init__() when instantiation!
a.fly() # I can not fly!
b = Animal(can_fly = True) # Calling __init__() when instantiation!
b.fly() # I CAN fly!
class
class Animal:
"""This is an Animal"""
def fly():
print("I can fly!")
a = Animal()
a.fly() # I can fly!
print(a.__doc__) # This is an Animal