python 类 内置方法 python类的内置函数_字符串

内置函数就是Python预先定义的函数,这些内置函数使用方便,无需导入,直接调用,大大提高使用者的工作效率,也更便于程序的阅读。截止到Python版本3.9.1,Python一共提供了69个内置函数。

如果你还没入门,或刚刚入门Python,那么,这篇文章非常适合你。为了方便记忆,木木老师会将这些内置函数分类介绍给大家。数学运算(7个)

类型转换(24个)

序列操作(8个)

对象操作(9个)

反射操作(8个)

变量操作(2个)

交互操作(2个)

文件操作(1个)

编译执行(5个)

装饰器(3个)

数学运算(7个)

abs:求数值的绝对值
print(abs(-2)) # 绝对值:2
divmod:返回两个数值的商和余数print(divmod(20,3)) # 求商和余数:(6,2)
max:返回可迭代对象中的元素中的最大值或者所有参数的最大值
print(max(7,3,15,9,4,13)) #求最大值:15
min:返回可迭代对象中的元素中的最小值或者所有参数的最小值print(min(5,3,9,12,7,2)) #求最小值:2
pow:返回两个数值的幂运算值或其与指定整数的模值
print(pow(10,2,3)) # 如果给了第三个参数. 表示最后取余:1
round:对浮点数进行四舍五入求值print(round(2.675, 2)) # 五舍六入:2.67
sum:对元素类型是数值的可迭代对象中的每个元素求和
print(sum([1,2,3,4,5,6,7,8,9,10])) # 求和:55

类型转换(24个)

bool:根据传入的参数的逻辑值创建一个新的布尔值print(bool(0)) # 数值0、空序列等值为:False
int:根据传入的参数创建一个新的整数
print(int(3.6)) # 整数:3
float:根据传入的参数创建一个新的浮点数print(float (3)) # 浮点数:3.0
complex:根据传入参数创建一个新的复数
print(complex (1,2)) # 复数:1+2j
str:将数据转化为字符串print(str(123)+'456') #123456
bytearray:根据传入的参数创建一个新的字节数组
ret = bytearray('alex' ,encoding ='utf-8')print(ret[0]) #97print(ret) #bytearray(b'alex')ret[0] = 65 #把65的位置A赋值给ret[0]print(str(ret)) #bytearray(b'Alex')
bytes:根据传入的参数创建一个新的不可变字节数组bs = bytes('今天吃饭了吗', encoding='utf-8')print(bs) #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'
memoryview:根据传入的参数创建一个新的内存查看对象
v = memoryview(b'abcefg')print(v[1]) # 98
ord:返回Unicode字符对应的整数print(ord('中')) # '中'字在编码表中的位置:20013
chr:返回整数所对应的Unicode字符
print(chr(65)) # 已知码位求字符:A
bin:将整数转换成2进制字符串print(bin(10)) # 二进制:0b1010
oct:将整数转化成8进制数字符串
print(oct(10)) # 八进制:0o12
hex:将整数转换成16进制字符串print(hex(10)) # 十六进制:0xa
tuple:根据传入的参数创建一个新的元组
print(tuple([1,2,3,4,5,6])) # (1, 2, 3, 4, 5, 6)
list:根据传入的参数创建一个新的列表print(list((1,2,3,4,5,6))) # [1, 2, 3, 4, 5, 6]
dict:根据传入的参数创建一个新的字典
print(dict(a = 1,b = 2)) # 创建字典: {'b': 2, 'a': 1}
range:根据传入的参数创建一个新的range对象for i in range(15,-1,-5):print(i)# 15# 10# 5# 0
set:根据传入的参数创建一个新的集合
a = set(range(10))print(a) # 创建集合:{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
frozenset:根据传入的参数创建一个新的不可变集合a = frozenset(range(10))print(a) #frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
enumerate:根据可迭代对象创建枚举对象
lst = ['one','two','three','four','five']for index, el in enumerate(lst,1): # 把索引和元素一起获取,索引默认从0开始. 可以更改print(index)print(el)# 1# one# 2# two# 3# three# 4# four# 5# five
iter:根据传入的参数创建一个新的可迭代对象lst = [1, 2, 3]for i in iter(lst):print(i)# 1# 2# 3
slice:根据传入的参数创建一个新的切片对象
lst = '你好啊'it = reversed(lst) # 不会改变原列表. 返回一个迭代器, 设计上的一个规则print(list(it)) #['啊', '好', '你']lst = [1, 2, 3, 4, 5, 6, 7]print(lst[1:3:1]) #[2,3]s = slice(1, 3, 1) # 切片用的print(lst[s]) #[2,3]
super:根据传入的参数创建一个新的子类和父类关系的代理对象class A:def add(self, x):y = x+1print(y)class B(A):def add(self, x):super().add(x)b = B()b.add(2) # 3
object:创建一个新的object对象
class A:passprint(issubclass(A,object)) #默认继承object类 # Trueprint(dir(object))# ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

序列操作(8个)

all:判断可迭代对象的每个元素是否都为True值print(all([1,'hello',True,9])) #True
any:判断可迭代对象的元素是否有为True值的元素
print(any([0,0,0,False,1,'good'])) #True
filter:使用指定方法过滤可迭代对象的元素def is_odd(n):return n % 2 == 1newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])print(newlist) # [1, 3, 5, 7, 9]
map:使用指定方法去作用传入的每个可迭代对象的元素,生成新的可迭代对象
def f(i):return ilst = [1,2,3,4,5,6,7,]it = map(f, lst) # 把可迭代对象中的每一个元素传递给前面的函数进行处理. 处理的结果会返回成迭代器print(list(it)) #[1, 2, 3, 4, 5, 6, 7]
next:返回可迭代对象中的下一个元素值it = iter([1, 2, 3, 4, 5])while True:try:x = next(it)print(x)except StopIteration:break# 1# 2# 3# 4# 5
reversed:反转序列生成新的可迭代对象
print(list(reversed([1,2,3,4,5]))) # [5, 4, 3, 2, 1]
sorted:对可迭代对象进行排序,返回一个新的列表a = [5,3,4,2,1]print(sorted(a,reverse=True)) # [5, 4, 3, 2, 1]
zip:聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器
my_list = [11,12,13]my_tuple = (21,22,23)print(list(zip(my_list,my_tuple))) # [(11, 21), (12, 22), (13, 23)]

对象操作(9个)

help:返回对象的帮助信息print(help(str)) #查看字符串的用途
dir:返回对象或者当前作用域内的属性列表
print(dir(tuple)) #查看元组的方法
id:返回对象的唯一标识符s = 'alex'print(id(s)) # 139783780730608
hash:获取对象的哈希值
s = 'alex'print(hash(s)) #-168324845050430382lst = [1, 2, 3, 4, 5]print(hash(lst)) #报错,列表是不可哈希的
type:返回对象的类型,或者根据传入的参数创建一个新的类型dict = {'Name': 'Zara', 'Age': 7}print('Variable Type : %s' % type (dict)) # Variable Type : 
len:返回对象的长度
mylist = ['apple', 'orange', 'cherry']x = len(mylist)print(x) # 3
ascii:返回对象的可打印表字符串表现方式s = 5print(ascii(s)) # 5format:格式化显示值s = 'hello world!'print(format(s, '^20')) #居中print(format(s, '<20')) #左对齐print(format(s, '>20')) #右对齐# hello world!# hello world!# hello world!
vars:返回当前作用域内的局部变量和其值组成的字典,或者返回对象的属性列表
class Person:name = 'John'age = 36country = 'norway'x = vars(Person)print(x)# {'__module__': '__main__', 'name': 'Bill', 'age': 63, 'country': 'USA', '__dict__': , '__weakref__': , '__doc__': None}

反射操作(8个)

__import__:动态导入模块import osname = input('请输入你要导入的模块:')__import__(name) # 可以动态导入模块
isinstance:判断对象是否是类或者类型元组中任意类元素的实例
arg=123print(isinstance(arg, int)) # 输出True
issubclass:判断类是否是另外一个类或者类型元组中任意类元素的子类class A:passclass B(A):passprint(issubclass(B,A)) # 返回 True
hasattr:检查对象是否含有属性
class Coordinate:x = 10y = -5z = 0point1 = Coordinate()print(hasattr(point1, 'x'))print(hasattr(point1, 'y'))print(hasattr(point1, 'z'))print(hasattr(point1, 'no')) # 没有该属性# True# True# True# False
getattr:获取对象的属性值class Person():age = 14Tom = Person()print(getattr(Tom,'age')) # 14
setattr:设置对象的属性值
class A():name = '吊车尾'a = A()setattr(a, 'age', 24)print(a.age) # 24
delattr:删除对象的属性class Person:def __init__(self, name, age):self.name = nameself.age = agetom = Person('Tom', 35)print(dir(tom)) # ['__doc__', '__init__', '__module__', 'age', 'name']delattr(tom, 'age')print(dir(tom)) # ['__doc__', '__init__', '__module__', 'name']s
callable:检测对象是否可被调用
a = 10print(callable(a)) #False 变量a不能被调用

变量操作(2个)

globals:返回当前作用域内的全局变量和其值组成的字典x = 'hello'a = 8888888print(globals()) #返回一个全局变量的字典,包括所有导入的变量x,a# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.sourcefileloader>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': 'D:/Pythonproject/111/global.py', '__cached__': None, 'x': 'hello', 'a': 8888888}
locals:返回当前作用域内的局部变量和其值组成的字典
print(locals())# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.sourcefileloader object at>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_locals_example.py', '__cached__': None}

交互操作(2个)

print:向标准输出对象打印输出print(1,2,3) # 1 2 3
input:读取用户输入值
a = input('请输入你的姓名') #输入:张三print(a) # 张三

文件操作(1个)

open:使用指定的模式和编码打开文件,返回文件读写对象f = open('file',mode='r',encoding='utf-8')f.read()f.close()

编译执行(5个)

compile:将字符串编译为代码或者AST对象,使之能够通过exec语句来执行或者eval进行求值
code = 'for i in range(3): print(i)'com = compile(code, '', mode='exec')exec(com)# 0# 1# 2
eval:执行动态表达式求值code = '5+6+7'com = compile(code, '', mode='eval')print(eval(com)) # 18
exec:执行动态语句块
s = 'for i in range(5): print(i)'a = exec(s)# 0# 1# 2# 3# 4
repr:返回一个对象的字符串表现形式(给解释器)class test:def __init__(self,name,age):self.age = ageself.name = namedef __repr__(self):return 'Class_Test[name='+self.name+',age='+str(self.age)+']'t = test('Zhou',30)print(t) # Class_Test[name=Zhou,age=30]
breakpoint:暂停脚本的执行,允许在程序的内部手动浏览

装饰器(3个)

property:标示属性的装饰器
class C:def __init__(self):self._name = ''@propertydef name(self):'''i'm the 'name' property.'''return self._name@name.setterdef name(self,value):if value is None:raise RuntimeError('name can not be None')else:self._name = value
classmethod:标示方法为类方法的装饰器class C:@classmethoddef f(cls,arg1):print(cls)print(arg1)
staticmethod:标示方法为静态方法的装饰器
class Student(object):def __init__(self,name):self.name = name@staticmethoddef sayHello(lang):print(lang)if lang == 'en':print('Welcome!')else:print('你好!')

收集不易,记得给木木一个小反馈哦~

PS:由于空格原因,这些代码直接复制运行不了哦~