python所有内置函数的简单使用

一、官方网址

内置函数 — Python 3.10.1 文档https://docs.python.org/zh-cn/3.10/library/functions.html#isinstance

二、实验

# A
print(abs(-1))  # 1
print(abs(1.265))  # 1.265
print(abs(1+1j))  # 1.4142135623730951

# ai = aiter([1,2,3,4,5,6])  # 只支持3.10版本,用法与iter类似
# print(next(ai))

print(all([0,1,2,3,4,5,6]))  # False, 全为真时输出才是True
print(all([1,2,3,4,5,6]))  # True

print(any([0,1,2,3,4,5,6]))  # True, 任意一个为真时输出就是True
print(any([0,0]))  # False

print(ascii("我[0,0]我"))  # '\u6211[0,0]\u6211',转化成ASCII 字符,非 ASCII 字符会用 \x、\u 和 \U 进行转义。


# B
print(bin(5))  # 0b101, 将整数转变为以“0b”前缀的二进制字符串。

print(bool([0,1,2,3,4]))  # True

# breakpoint()  # 断电,程序执行到这个地方时会停止,等待调试人员输入指令

print(bytearray("12345,上山打老虎!", encoding="utf-8"))  # bytearray(b'12345,\xe4\xb8\x8a\xe5\xb1\xb1\xe6\x89\x93\xe8\x80\x81\xe8\x99\x8e\xef\xbc\x81')

print(bytes("12345,上山打老虎!", encoding="utf-8"))  # b'12345,\xe4\xb8\x8a\xe5\xb1\xb1\xe6\x89\x93\xe8\x80\x81\xe8\x99\x8e\xef\xbc\x81'


# C
def b():
    pass
print(callable(123))  # False, 如果参数 object 是可调用的就返回 True,否则返回 False。
print(callable(b))  # True

print(chr(97))  # a, 返回 Unicode 码位为整数 i 的字符的字符串格式。

class C:
    @classmethod  # classmethod()的使用方式
    def f(cls, arg1, arg2):
        print("nice")

c = compile("for i in range(0,2): print(i)",'','exec')  # 首先编译为字节代码对象(exec对象)
print(c)
exec(c)  # 0,1  ,再通过该种类的编译器去执行

print(complex(1,2))  # (1+2j)

# D
setattr(C, "name", "猪坚强")
print(C.name)  # 猪坚强
delattr(C, "name")
print(dir(C))  # 不再有name属性

print(divmod(1, 2))  # (0, 1), 返回(商,余数)

# E
for index,value in enumerate([1,2,3,4]):
    print(index,value)  # 0 1, 1 2, ...

print(eval("[1,2,3]"))  # [1, 2, 3], 执行字符串中的语句(单条执行)
exec('''  
print("我是exec")
C().f(1,2)
''')  # 执行字符串中的语句(批量执行)

# F
print(list(filter(lambda x: x%2==1, [1,2,3,4])))  # [1, 3]

print(float(0))  # 0.0

print(format("12345", "1<10"))  # 1234511111,填充为10个字符,并且以“1”填充

print(frozenset({1,2,3,3,3}))  # 不可变集合


# G
print("-----------------分界线--------------------")
def g():
    gg = 123

print(globals())  # 全局变量字典,但对于函数内部的值只返回对象 : {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001438A5F08E0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/pycharm/Projects/viscanner_interface/common/mytest001.py', '__cached__': None, 'b': <function b at 0x000001438AAC2160>, 'C': <class '__main__.C'>, 'c': <code object <module> at 0x000001438AB40710, file "", line 1>, 'i': 1, 'index': 3, 'value': 4, 'g': <function g at 0x000001438AAC21F0>}

# H
class H:
    name = "123"
print(hasattr(H, "name"))  # True, 如果字符串是对象的属性之一的名称,则返回 True,否则返回 False。
print(hasattr(H, "www")) # Flase

print(hash(H))  # 返回一个hash值

help(H)  # 查看帮助文档

print(hex(123))  # 0x7b, 将整数转换为以“0x”为前缀的小写十六进制字符串。

# I
print(id(H))  # 返回内存中该对象的唯一ID

# s = input('--> ')  # 输入什么则展示什么
# print(s)

print(int("10"))

print(isinstance("123",str))  # True, 判断类型
print(isinstance("123",int))  # False

class H1(C):
    pass
print(issubclass(C,H))  # False
print(issubclass(C,H1))  # False
print(issubclass(H1,C))  # True

it = iter([1,2,3,4,5])
print(next(it))  # 1

# L
print(len([1,2,3,4,5,0,0,0]))  # 8

print(list("[1,2,3,4]"))  # ['[', '1', ',', '2', ',', '3', ',', '4', ']']

print(locals())  # 更新并返回表示当前本地符号表的字典。 在函数代码块但不是类代码块中调用 locals() 时将返回自由变量。
def df1():
    a001 = 999
    print(locals())
df1()  # {'a001': 999}

print(list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])))  # [1, 4, 9, 16, 25], 返回一个将 function 应用于 iterable 中每一项并输出其结果的迭代器。

# M
print(max([1, 2, 3, 4, 5]))  # 5
print(max([1, 2, 3, 4, 5], [10, 20, 30, 40, 50]))  # [10, 20, 30, 40, 50]

print(min([1, 2, 3, 4, 5]))  # 1
print(min([1, 2, 3, 4, 50], [10, 20, 30, 40, 5]))  # [1, 2, 3, 4, 50]

print(next(it))  # 2

# O
print(oct(123))  # 0o173 , 将一个整数转变为一个前缀为“0o”的八进制字符串。

# open("../files.txt")  # 打开文件

print(ord('a'))  # 97

# P
print(pow(2, 5))  # 32, 返回 2 的 5 次幂

print("hi, 我是print")

class P():
    @property
    def p1(self):
        return 1

    def  __repr__(self):
        return "[1,2,3]"

print(P().p1)  # 1, 将函数变属性

# R
print(range(2))  # range(0, 2)

print(repr(P))  # 返回对象的可打印形式字符串。
print(repr({'runoob': 'runoob.com', 'google': 'google.com'}))  # 字符串 {'runoob': 'runoob.com', 'google': 'google.com'}

print(list(reversed([1,2,3,4,5])))  # [5, 4, 3, 2, 1]

print(round(5.5))  # 6, 四舍五入
print(round(-0.5))  # 0

# S
print(set("1,2,3"))  # {',', '3', '1', '2'}, 返回可变集合

setattr(P, "name", "value")  # 设置属性值
print(P.name)  # value

print(slice(5))  # slice(None, 5, None)
print([1,2,3,4,5,6,7,8,9][slice(5)])  # [1, 2, 3, 4, 5]

print(sorted([1,2,3,4,5], key=None, reverse=True))  # [5, 4, 3, 2, 1]

class S(object):
    @staticmethod
    def s001():
        return 1
print(S.s001())  # 1

print(str([1,2,3,4]))  # [1, 2, 3, 4]  (字符串)

print(sum([1,2,3,4,5]))  # 15

class A1:
    def add(self, x):
        y = x + 1
        print(y)

class B1(A1):
    def add(self, x):
        super().add(x)  # super() 函数是用于调用父类(超类)的一个方法。

b = B1()
b.add(2)  # 3

# T
print(tuple([1,2,3,4]))  # (1, 2, 3, 4)

print(type([1]))  # <class 'list'>

# V
print(vars(A1))  # 返回模块、类、实例或任何其它具有 __dict__ 属性的对象的 __dict__ 属性。 {'__module__': '__main__', 'add': <function A1.add at 0x00000289F87338B0>, '__dict__': <attribute '__dict__' of 'A1' objects>, '__weakref__': <attribute '__weakref__' of 'A1' objects>, '__doc__': None}

# Z
for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
    print(item)  # (1, 'sugar')/(2, 'spice')/(3, 'everything nice')

# _
eggs = 110
sausage = 120
_temp = __import__('common.mytest001', globals(), locals(), ['eggs', 'sausage'], 0)
eggs1 = _temp.eggs
saus = _temp.sausage
print(eggs1)  # 110 因为导入的是模块本身,则会出现两次,从其他模块导入,则不会有问题
print(saus)  # 120



















版权声明:本文为weixin_43431593原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。