全国服务热线:

15861139266

68个Python内置函数(下)_苏州机器视觉培训_苏州上位机培训_苏州工业机器人培训
发布时间:2024-03-13 15:24:00 点击次数:803

和作用域相关

locals() 返回当前作用域中的名字

globals() 返回全局作用域中的名字

def func():

    a = 10

    print(locals())  # 当前作用域中的内容

    print(globals())  # 全局作用域中的内容

    print("今天内容很多")

func()

# {'a': 10}

# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': 

# <_frozen_importlib_external.SourceFileLoader object at 0x0000026F8D566080>, 

# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' 

# (built-in)>, '__file__': 'D:/pycharm/练习/week03/new14.py', '__cached__': None,

#  'func': <function func at 0x0000026F8D6B97B8>}

# 今天内容很多

和迭代器生成器相关

range() 生成数据

next() 迭代器向下执行一次, 内部实际使⽤用了__ next__()⽅方法返回迭代器的下一个项目

iter() 获取迭代器, 内部实际使用的是__ iter__()⽅方法来获取迭代器

for i in range(15,-1,-5):

    print(i)

# 15

# 10

# 5

# 0

lst = [1,2,3,4,5]

it = iter(lst)  #  __iter__()获得迭代器

print(it.__next__())  #1

print(next(it)) #2  __next__()  

print(next(it))  #3

print(next(it))  #4

字符串类型代码的执行

eval() 执行字符串类型的代码. 并返回最终结果

exec() 执行字符串类型的代码

compile() 将字符串类型的代码编码. 代码对象能够通过exec语句来执行或者eval()进行求值

s1 = input("请输入a+b:")  #输入:8+9

print(eval(s1))  # 17 可以动态的执行代码. 代码必须有返回值

s2 = "for i in range(5): print(i)"

a = exec(s2) # exec 执行代码不返回任何内容


# 0

# 1

# 2

# 3

# 4

print(a)  #None


# 动态执行代码

exec("""

def func():

    print(" 我是周杰伦")

""" )

func()  #我是周杰伦

code1 = "for i in range(3): print(i)"

com = compile(code1, "", mode="exec")   # compile并不会执行你的代码.只是编译

exec(com)   # 执行编译的结果

# 0

# 1

# 2


code2 = "5+6+7"

com2 = compile(code2, "", mode="eval")

print(eval(com2))  # 18


code3 = "name = input('请输入你的名字:')"  #输入:hello

com3 = compile(code3, "", mode="single")

exec(com3)

print(name)  #hello

输入输出

print() : 打印输出

input() : 获取用户输出的内容

print("hello", "world", sep="*", end="@") # sep:打印出的内容用什么连接,end:以什么为结尾

#hello*world@

内存相关

hash() : 获取到对象的哈希值(int, str, bool, tuple). hash算法:(1) 目的是唯一性 (2) dict 查找效率非常高, hash表.用空间换的时间 比较耗费内存


s = 'alex'print(hash(s))  #-168324845050430382lst = [1, 2, 3, 4, 5]print(hash(lst))  #报错,列表是不可哈希的  id() :  获取到对象的内存地址s = 'alex'print(id(s))  #2278345368944

文件操作相关

open() : 用于打开一个文件, 创建一个文件句柄

f = open('file',mode='r',encoding='utf-8')

f.read()

f.close()

模块相关

__ import__() : 用于动态加载类和函数

# 让用户输入一个要导入的模块

import os

name = input("请输入你要导入的模块:")

__import__(name)    # 可以动态导入模块

帮 助

help() : 函数用于查看函数或模块用途的详细说明

print(help(str))  #查看字符串的用途

调用相关

callable() : 用于检查一个对象是否是可调用的. 如果返回True, object有可能调用失败, 但如果返回False. 那调用绝对不会成功

a = 10

print(callable(a))  #False  变量a不能被调用

#

def f():

    print("hello")

    print(callable(f))   # True 函数是可以被调用的

查看内置属性

dir() : 查看对象的内置属性, 访问的是对象中的__dir__()方法

print(dir(tuple))  #查看元组的方法



立即咨询
  • 品质服务

    服务贴心周到

  • 快速响应

    全天24小时随时沟通

  • 专业服务

    授权率高,保密性强

  • 完善售后服务

    快速响应需求,及时性服务

直播课程
软件开发基础课程
上位机软件开发课
机器视觉软件开发课
专题课
联系方式
电话:15861139266
邮箱:75607802@qq.com
地址:苏州吴中区木渎镇尧峰路69号
关注我们

版权所有:大林机器视觉培训苏州办事处所有 备案号:苏ICP备14016686号-6

技术支持: 新易维软件