Python interview one hundred questions - comprehensive title (1)

table of Contents

  1. Difference read, readline and readlines of
  2. How to handle the type of date when JSON serialization
  3. Please use the code with statements describe the role
  4. Most frequently appearing character to get the file
  5. The role of decorator
  6. Judgment call is a function or method
  7. Please explain @classmethod and @staticmethod usage and differences
  8. What metaclass (metaclass) is the role of examples to illustrate
  9. hasattr (), getattr (), setattr () usage
  10. Please describe the role of lambda expressions

Difference 0.1read, readline and readlines of

Here Insert Picture Description

f = open('val.txt', 'r')

# 题2:
.read():读取文件的全部内容
.read(n):读取文件前n个字符
.seek(n):移动指针到n

.readline():读取文件第一行
.readline():再加一个,读取文件第二行
.readline(n):读取一行的前n个字符(n大于该行长度时,输出该行)

.readlines():读取文件的全部内容,根据\n分成每一行,放入列表
['hello world\n', 'python\n']
.readlines(n):读取字符数大于n的行
比如.readlines(3) ----> ['hello world\n']
.readlines(11) ----> ['hello world\n']	(hello world长度为11.readlines(12) ----> ['hello world\n', 'python\n'] (hello world长度不够,需要python行补上,大于12)

0.2 how to handle the type of date when JSON serialization

Here Insert Picture Description

# 题1
可处理:strintlisttupledictboolNone
但datetime不支持JSON序列化

# 题2:default
import json
from datetime import datetime, date

class DateToJson(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y年%m月%d日 %H:%M:%S')	# 格式化
        elif isinstance(obj, date):
            return obj.strftime('%Y年%m月%d日')
        else:
            return json.JSONEncoder.default(self, obj)

d = {'name': 'Bill', 'date':datetime.now()}
print(json.dumps(d, cls=DateToJson, ensure_ascii=False))	# 确保中文输出

to sum up
Here Insert Picture Description

Please use the code with statements describe the role

Here Insert Picture Description

# 题1
with语句适用于对资源进行访问的场合,确保不管使用过程是否发生异常都会执行必要的“清理”工作(释放资源)

f = open('file.txt', 'r')
print(f.read())
'''
1.没有关闭文件
2.即使关闭了文件,但在关闭之前如果抛出异常,仍然会无法关闭文件
'''
# 方法一
f = open('file.txt', 'r')
try:
	print(f.read())
except:
	print('异常')
finally:
	f.close()
	
# 方法二
with open('file.txt', 'r') as f:
	data = f.read()
	print(data)

# 题2
class MyClass:
    def __enter__(self):
        print('__enter__ is call')
        return self
    def process1(self):
        print('process1')
    def process2(self):
        x = 1 / 0   # 抛出异常
        print('process2')
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('__exit__ is call')
        print(f'type:{exc_type}')
        print(f'val:{exc_val}')
        print(f'trace:{exc_tb}')

with MyClass() as my:
    my.process1()
    my.process2()
__enter__ is call
process1
__exit__ is call
type:<class 'ZeroDivisionError'>
val:division by zero
trace:<traceback object at 0x000001DDE039D6C8>

to sum up
Here Insert Picture Description

04. get the highest frequency of characters appear in the file

Here Insert Picture Description

with open('val.txt', 'r') as f:
    data = f.read()

'''
key:在文本文件中出现的字符
value:int类型,key指定的字符出现的总次数
maxChar:当前出现的最多次数字符

'''
d = {}
maxChar = ''
for c in data:
    if c.isspace():
        continue    # 排除空格
    if d.get(c) is None:
        d[c] = 1
        if maxChar == '':
            maxChar = c
    else:
        d[c] += 1
        if d[maxChar] <d[c]:
            maxChar = c

print(maxChar)
print(d[maxChar])

to sum up
Here Insert Picture Description

Action 0.5 decorator

Here Insert Picture Description

# 题1
装饰器是一个函数,

# 题2
# 输出函数相关信息的装饰器函数
from functools import wraps

def log(flag):
    def decorate(func):
        @wraps(func)
        def _wrap(*args, **kwargs):
            try:
                if flag:	# 为真时才能调用add函数
                    func(*args, **kwargs)
                print('name:', func.__name__)
            except Exception as e:
                print(e.args)
        return _wrap

    return decorate

@log(True)
def add(a, b, c):
    print('sum:', a + b + c)

add(1, 2, 3)
sum: 6
name: add

to sum up
Here Insert Picture Description

0.6 judgment call is a function or method

Here Insert Picture Description

# 方法一
class MyClass:
    def process(self):
        pass

def process():
    pass

print(type(MyClass().process).__name__ == 'method')	# True
print(type(process))	# <class 'function'>

# 方法二
from types import MethodType, FunctionType

print(isinstance(MyClass().process, MethodType))	# True
print(isinstance(process, FunctionType))	# True

to sum up
Here Insert Picture Description

07. Please explain @classmethod and @staticmethod usage and differences

Here Insert Picture Description

'''
共同点:都是用来声明静态方法(不需要实例化类就能调用的方法)的。类名.方法名()

区别:
1.@staticmethod不需要表示自身对象的self和自身类的cls参数,就像普通函数一样定义
2.@classmethod也不需要self参数,但第二个参数需要表示自身的cls参数,避免硬编码。
'''
class MyClass:
    bar = 1 # 静态变量
    def __init__(self):
        self.count = 20     # 成员变量,需要实例化
    def process(self):
        print('process', self.count)

    @staticmethod
    def static_process():
        print('static_process')
        print(MyClass.bar)  # 不能直接print(bar),找不到;如果类名变为MyClass1,也要变为MyClass1.bar

    @classmethod
    def class_process(cls):
        print('class_process')
        print(cls.bar)  # cls就是类本身,类名变了也没事
        cls().process()
        print(cls().count)


MyClass.static_process()
MyClass.class_process()
MyClass.bar = 123
MyClass.static_process()    # 123

Summary
Here Insert Picture Description
If you want to get away directly classmethod

What is the role of 0.8 yuan class (the metaclass that) are examples to illustrate

Here Insert Picture Description

'''
metaclass:元类,类似于创建类的模板,所有的类都是通过他来创建的,可以自由控制类的创建过程。单例模式、ORM模式
'''

Here Insert Picture Description
to sum up
Here Insert Picture Description

0.9 hasattr (), getattr (), setattr () usage

Here Insert Picture Description

'''
hasattr:可以判断一个对象是否包含某个属性
getattr:可以获取对象中某个属性的值
setattr:可以设置对象中某个属性的值
'''

Here Insert Picture Description
to sum up
Here Insert Picture Description

10. Please describe the role of lambda expressions

Here Insert Picture Description

lambda表达式:匿名函数,可以作为参数值传入函数或方法

a = [('a', 1), ('b', 2), ('c', 3)]

a_1 = list(map(lambda x:x[0], a))
a_2 = list(map(lambda x:x[1], a))
print(a_1)	# ['a', 'b', 'c']
print(a_2)	# [1, 2, 3]

to sum up
Here Insert Picture Description

Published 21 original articles · won praise 5 · Views 1562

Guess you like

Origin blog.csdn.net/qq_36551226/article/details/104571895