Python技巧100题(八)

在这里插入图片描述

1.查询系统默认编码方式

fp = open('test.txt', 'w')
print(fp.encoding)
cp936

2.修改编码方式

fp = open('test.txt', 'w', encoding='utf-8')
print(fp.encoding)
utf-8

3.用递归实现阶乘

def factorial(n):
    """:return n!"""
    return 1 if n < 2 else n * factorial(n-1)

4.all([])的输出结果是多少

True

5.any([])的输出结果是多少

False

6.怎么判断对象时否可被调用

print([call(obj) for obj in (abs, str, 2)])
[True, True, False]

7.怎么列出对象的所有属性

使用dir函数获取对象的所有属性
import requests
print(dir(requests))

8.怎么得到类的实例没有而函数有的属性列表

class c:
    pass
obj = c()
def func():
    pass
print(sorted(set(dir(func)) - set(dir(obj))))
['__annotations__', '__call__', '__closure__', '__code__', '__defaults__', '__get__', '__globals__', '__kwdefaults__', '__name__', '__qualname__']        

9.函数中不想支持数量不定的定位参数,但是想支持仅限关键字参数,参数怎么定义

def f(a, *, b):
    return a, b
print(1, b=2) 
(1, 2)   

10.怎么给函数参数返回值注解

def function(text: str, max_len: 'int > 0' = 80) -> str:

人生漫漫其修远兮,网安无止境。
一同前行,加油!

猜你喜欢

转载自blog.csdn.net/qq_45924653/article/details/108182783