按字母顺序
a…
abs(x)
class Test:
def __abs__(self):
return f'{__class__}实现了__abs__'
print(
f'整数-1的绝对值:{abs(-1)}','\n',
f'浮点数-9.9的绝对值:{abs(-9.9)}','\n',
f'复数:{complex(1,2)}的绝对值:{abs(complex(1,2))} = 复数的模','\n',
f'Test的绝对值:{abs(Test())}',
)
"""
OUT:
整数-1的绝对值:1
浮点数-9.9的绝对值:9.9
复数:(1+2j)的绝对值:2.23606797749979 = 复数的模
Test的绝对值:<class '__main__.Test'>实现了__abs__
"""
all(iterable)
print(all([1,2,3,4,0,True]))
print(all([1,2,3,4,41,True]))
print(all(123))
any(iterable)
print(any([]))
print(any([1,0,0,0,0,0,0,0]))
print(any([False,False,False]))
ascii(object)
class Test:
def __repr__(self):
return "Hello repr"
print(ascii(Test()))
print(ascii('\n'))
print(ascii('a'))
b…
bin(x)
class Test:
def __index__(self):
return 12
print(bin(1))
print(type(bin(1)))
print(format(1,'b'))
print(format(1,'#b'))
print(f'{1:b}')
print(f'{1:#b}')
print(bin(Test()))
bool(x)
print(bool(False))
print(bool(0))
print(bool([]))
print(bool(()))
print(bool({}))
print(bool(''))
print(bool(complex(0,0)))
breakpoint()
bytearray()
print(bytearray(4))
print(len(bytearray(4)))
res = bytearray('Hello world',encoding='utf8')
print(res)
res = bytearray('Hello world')
print(res)
bytes()
c…
callable()
def func1():
return "func1"
print(callable(func1))
"""
Python中函数是可调用对象这是不容置疑的,所有语言的函数都是可以调用的
"""
class Test:
def func2(self):
return "func2"
print(callable(Test.func2))
"""
Python中对象的实例方法,类方法和静态方法都是可调用对象
"""
print(callable(Test))
"""
Python中类是可调用对象,类() -> 实例化 -> 返回一个实例
"""
print(callable(Test()))
"""
一个没有__call__()的类的实例是不能被调用的
"""
class Test:
def __call__(self, *args, **kwargs):
return f'{__class__}实现了__call__(),所以Test类的实例是可调用的!!!'
print(callable(Test()))
test1 = Test()
res = test1()
print(res)
classmethod()
class Test:
@classmethod
def classfunc(cls,name,age):
return f"{name} is {age} old"
test1 = Test()
res = test1.classfunc('zhangsan',12)
res_ = Test.classfunc('zhangsan',12)
print(res)
print(res_)
compile()
complex()
print(complex(1,2))
d…
delattr(object,name)
class Test:
def __init__(self, name,age):
self.name = name
self.age = age
test1 = Test(name='zhangsan',age=30)
print(test1.name)
delattr(test1,'name')
print(test1.name)
d1 = dict(k1='v1',k2='v2')
print(d1['k1'])
delattr(d1,'k1')
print(d1['k1'])
dir()
"""
如果对象是模块对象,则列表包含模块的属性名称。
如果对象是类型或类对象,则列表包含它们的属性名称,并且递归查找所有基类的属性。
否则,列表包含对象的属性名称,它的类属性名称,并且递归查找它的类的所有基类的属性。
"""
class Shape:
def __dir__(self):
return ['area', 'perimeter', 'location']
s = Shape()
dir(s)
dict()
d1 = dict(k1='v1',k2='v2')
print(d1)
divmod()
"""
它将两个(非复数)数字作为实参,并在执行整数除法时返回一对商和余数。对于混合操作数类型,适用双目算术运算符的规则。对于整数,结果和 (a // b, a % b) 一致。对于浮点数,结果是 (q, a % b) ,q 通常是 math.floor(a / b) 但可能会比 1 小。在任何情况下, q * b + a % b 和 a 基本相等;如果 a % b 非零,它的符号和 b 一样,并且 0 <= abs(a % b) < abs(b) 。
"""
print(divmod(3,5))
print(divmod(5,2))
print(divmod(-5.2,2))
e…
enumerate(iterable,start)
list1 = ['kobe','wade','james','paul']
print(list(enumerate(list1, start=0)))
print(list(enumerate(list1, start=10)))
list1 = ['kobe','wade','james','paul']
def enumerate(seq,start=0):
for one in seq:
yield start, one
start += 1
res = enumerate(list1,start=0)
while True:
try:
print(next(res))
except StopIteration:
break
eval(expression[,gloabals][,locals])
rs = eval('1+8')
print(rs)
rs = eval('a+c',{'a':5},{'c':9})
print(rs)
exec()
f…
filter(function, iterable)
a = list(range(1,10))
list(filter(lambda i:i%2==0, a))
def get_oushu(i):
if i % 2 == 0:
return True
else:
return False
list(filter(get_oushu, a))
float()
float('+1.23')
float(' -12345\n')
float('1e-003')
float('+1E6')
float('-Infinity')
class Test:
def __init__(self,num):
self.num = num
def __float__(self):
if isinstance(self.num,int):
return float(self.num)
else:
return 1.0
t1 = Test('a')
t2 = Test(12)
float(t1),float(t2)
format(string[,spec])
format("hello world")
format(12,'b')
frozenset([,iterable])
frozenset([1,2,3,4])
type(frozenset([1,2,3,4]))
g…
getattr(obj,attr[,default])
class Test:
def __init__(self,name):
self.name = name
t1 = Test('张三')
getattr(t1,"name")
t1.name
getattr(t1,"age",10)
globals()
h…
hasattr()
class Test:
def __init__(self, name ):
self.name = name
t1 = Test("zhangsan")
def hasAttr(obj,attr):
try:
getattr(obj,attr)
return True
except AttributeError:
return False
hasAttr(t1,'name'),hasAttr(t1,'age')
hasattr(t1,'name'),hasattr(t1,'age')
hash()
class Test:
def __hash__(self):
return 123456789
hash(Test())
hash(1.0)
hash('Hello world')
help(obj)
hex(x)
if isinstance(x,int):
hex(12)
else:
class Test:
def __index__(self):
return 12
hex(Test())
i…
id(obj)
input()
s = input('-->')
--> "Hello world"
s
int()
isinstance(object, classinfo)
issubclass()
iter(obj)
L…
len()
list([iterable])
locals()
m…
map(function,iterable)
map(lambda x:x**2, [1,2,3,4])
list(map(lambda x:x**2, [1,2,3,4]))
max()
max([12,4,5,6,7])
max(12,24)
memoryview()
min()
n…
next()
iterator = iter([1,2,3,4])
type(iterator)
while True:
try:
print(next(iterator))
except StopIteration:
print("end")
break
"""
1
2
3
4
end
"""
o…
object()
oct()
open()
ord()
ord('a')
chr(97)
p…
pow(base, exp[, mod])
if mod不传参数:
return base的exp次方
else:
return base的exp次方对mod求余
pow(2,4),pow(2,4,3)
print()
property()
r…
range()
range(start,stop.step)
repr()
reversed()
list(reversed([1,2,3,4,5]))
round()
round(5.342532534,2)
s…
set()
setattr(obj,attr[,default])
slice()
sorted()
staticmethod()
class Test:
@staticmethod
def func1():
return "this is a static method!"
str()
sum()
super()
t…
tuple()
if 有实参:实参是一个可迭代对象:
tuple([1,2,3])
else 没有实参:
return 一个空数组 tuple()
type(obj)
type('hello'),type(12),type([1,2,3]),type((1,2,3)),type({1:2})
(str, int, list, tuple, dict)
v…
vars(obj)
z…
zip(*iterables)
zip([1,2,3,4],['zhangsan','lisi','wangwu','maliu'])
list(zip([1,2,3,4],['zhangsan','lisi','wangwu','maliu']))
…
__ import __()
重要的函数
结语
对于一些函数没有展开说,因为这些函数真的很重要,我准备在后面花时间用一个一个的专题好好整理出这些重要的内置函数 为什么这么说呢,因为我在很多优秀的框架的源码里面屡次看到它们的身影。
|