面试总结 持续更新中

day001

1、PEP8规范


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

2、了解bytes、str与unicode的区别

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

unicode字符转换成二进制数据,必须使用encode方法。

二进制数据转换成unicode字符,必须使用decode方法。

"""
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'你好')

总结:

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

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

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

print(to_str('你好'))
  • python3中,bytes是一种包含8个bit的序列,str是一种包含unicode字符的序列。不能以>或+等操作符来操作
  • python2中,str是一种包含8个bit的序列,unicode是一种包含unicode字符的序列。如果str只含有7位ascii字符,那么可以通过相关操作符来同时使用时str与unicode

3、面试题

以下结果输出结果为多少?

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.

猜你喜欢

转载自www.cnblogs.com/bladecheng/p/11183444.html