python版本为3.8.1
示例后的注释为打印值
temp = abs(-1.3) # 1.3 ==〉 1.3为print(temp)的值
compile:
"""
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
将 source 编译成代码或 AST 对象。代码对象可以被 exec() 或 eval() 执行
source:常规的字符串、字节字符串,或者 AST 对象
filename:实参需要是代码读取的文件名;如果代码不需要从文件中读取,可以传入一些可辨识的值(经常会使用 '<string>')
mode:实参指定了编译代码必须用的模式
source是语句序列,可以是 'exec';
source是单一表达式,可以是 'eval';
source是单个交互式语句,可以是 'single'
"""
s = """
def a1():
list1 = [x*2 for x in range(5)]
print(list1)
a1()
"""
temp = compile(source=s, filename='<string>', mode='exec')
exec(temp) # [0, 2, 4, 6, 8]
test.py文件的内容:
print('Hello!')
with open('test.py') as f1:
src = f1.read()
temp = compile(src, 'test.py', 'single')
eval(temp) # Hello!
complex:
# complex([real[, imag]]) 返回值为 real + imag*1j 的复数
temp = complex("10+2j") # (10+2j)
abs:
# abs(x)返回绝对值
temp = abs(-1.3) # 1.3
all:
# all(iterable)iterable所有元素为真(或迭代为空),返回True,否则返回False
temp = all((1, 2, True, 1)) # True
temp = all(()) # True
any:
# any(iterable)任一元素为真,返回True,否则返回False
temp = any((0, False, 1)) # True
temp = any(()) # False
ascii:
# ascii(object)返回对象可打印字符串
temp = ascii('python@.\n加油\t') # 'python@.\n\u52a0\u6cb9\t'
bin:
# bin(x)将一个整数转变为一个前缀为“0b”的二进制字符串
temp = bin(-7) # -0b111
# 不一定要前缀的做法
temp = f'{-7: #b}' # -0b111
temp = f'{-7: b}' # -111
bytearray:
# bytearray(source=None, encoding=None, errors='strict')
temp = bytearray('欢迎', encoding='utf8') # '\xe6\xac\xa2\xe8\xbf\x8e'
temp = bytearray(4) # '\x00\x00\x00\x00'
temp = bytearray([1, 19, 255]) # '\x01\x13\xff'
callable:
# callable(object)参数 object 是可调用的就返回 True,否则返回 False。
class test_class():
temp = 'test class'
temp = callable(test_class()) # False
temp = callable(test_class) # True
chr:
# chr(i)返回 Unicode 码位为整数 i 的字符的字符串格式
temp = chr(100) #d
@classmethod:
# @classmethod把一个方法封装成类方法
# 类方法的调用可以在类上进行 (例如 C2.f1()) 也可以在实例上进行 (例如 C2().f1())
class C2():
@classmethod
def f1(cls, arg1, *args):
temp_list = []
temp_list.append(arg1)
for arg in args:
temp_list.append(arg)
return temp_list
temp = C2.f1('a1', 'a2', '3') # ['a1', 'a2', '3']
delattr,setattr,getattr,dir:
# delattr(object, name)实参是一个对象和一个字符串。该字符串必须是对象的某个属性。如果对象允许,该函数将删除指定的属性。 # setattr(object, name, value)其参数为一个对象、一个字符串和一个任意值。 字符串指定一个现有属性或者新增属性。 函数会将值赋给该属性,只要对象允许这种操作。 # getattr(object, name[, default])返回对象命名属性的值。name 必须是字符串 # dir([object])如果没有实参,则返回当前本地作用域中的名称列表。如果有实参,它会尝试返回该对象的有效属性列表。 class C3(): def __init__(self, id, name, age): self._id = id self._name = name self._age = age temp=C3(1001, 'a1', 20) getattr(temp, '_id') # 1001 dir(temp) # [..., '_age', '_id', '_name'] delattr(temp, '_name') dir(temp) # [..., '_age', '_id'] setattr(temp, '_name2', 'AQ') dir(temp) # [..., '_age', '_id', '_name2']
divmod:
# divmod(a, b)它将两个(非复数)数字作为实参,并在执行整数除法时返回一对商和余数。
temp = divmod(10, 3) # (3, 1)
enumerate:
# enumerate(iterable, start=0)返回一个枚举对象。iterable 必须是一个序列,或 iterator,或其他支持迭代的对象。
temp = list(enumerate(['A1', 'CB', 6], 3)) # [(3, 'A1'), (4, 'CB'), (5, 6)]
temp = list(enumerate({1: 'a', 'a2': 'v1'}.values())) # [(0, 'a'), (1, 'v1')]