Continuously updated summary of the interview

day001

1, PEP8 specification


- 使用space(空格)来表示缩进,而不要用tab(制表符)
- 和语法相关的每一层缩进都要用4个空格来表示
- 每行的字符数不应超过79
- 对于占据多行的长表达式来说,除了首行之外的其余各行都应该在通常的缩进级别之上再加上4个空格
- 文件中函数与类之间应该用两个空行隔开
- 在同一个类中,各方法之间应该用一个空行隔开

2, understand the difference between bytes, str and unicode of

python3:  bytes、str
  """
bytes包含原始的8个bit位
str包含unicode字符
  """
python2:  str、unicode
  """
str包含8个bit位
unicode包含unicode字符
  """

unicode characters are converted into binary data, encode method must be used.

Convert the binary data into unicode characters, you must use the decode method.

"""
python3:
"""
def to_str(bytes_or_str):
    if isinstance(bytes_or_str, bytes):
        value = bytes_or_str.decode('utf-8')
    else:
        value = bytes_or_str
    return value


def to_bytes(bytes_or_str):
    if isinstance(bytes_or_str, str):
        value = bytes_or_str.encode('utf-8')
    else:
        value = bytes_or_str
    return value

print(to_bytes("你好"))


"""
python2
"""
def to_bytes(uncicode_or_str):
    if isinstance(uncicode_or_str, str):
        value = uncicode_or_str.decode('utf-8')
    else:
        value = uncicode_or_str
    return value


def to_unicode(uncicode_or_str):
    if isinstance(uncicode_or_str, unicode):
        value = uncicode_or_str.encode('utf-8')
    else:
        value = uncicode_or_str
    return value


print to_bytes('你好')
print to_unicode(u'你好')

to sum up:

# python2
print type('你好'.decode('utf-8'))  ==> unicode

print type('你好')  ==> str

# python3
print('你好'.decode('utf-8'))  ==> 报错

print(to_str('你好'))
  • In python3, bytes is an eight-bit sequence comprises, str is a sequence of characters comprising unicode. Can not> operator or the like operates +
  • In python2, str is an eight-bit sequence comprising, a sequence unicode unicode characters comprising. If str contains only seven ascii characters, then the time can be used simultaneously by the operator associated with the unicode str

3, face questions

The following output is the result of how much?

def multipliers():
  return [lambda x : i * x for i in range(4)]

print([m(2) for m in multipliers()])
上面代码输出的结果是[6, 6, 6, 6] (不是我们想的[0, 2, 4, 6]).

产生这个结果的主要原因是python闭包的延迟绑定。这意味着内部函数被调用时,参数的值在闭包内进行查找.

当任何由multipliers()返回的函数被调用时,i的值将在附近的范围进行查找。那时,不管返回的函数是否被调用,for循环已经完成,i被赋予了最终的值3.

Guess you like

Origin www.cnblogs.com/bladecheng/p/11183444.html