python内置函数

python标准库目录第一是python的介绍,第二条python按字母排序的内置函数,一共68个
就是可以直接写这个函数加个括号放入变量就可以执行的。
内置的函数在介绍中的文档:“The library also contains built-in functions and exceptions — objects that can be used by all Python code without the need of an import statement. Some of these are defined by the core language, but many are not essential for the core semantics and are only described here.。”意思就是在python中已经定义好了很多内置函数,直接调用就行了,底层已经用C++写好如何实现这些函数的功能


这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

(1)min(iterable, *[,key,defalult])
返回可迭代对象中最小的一个,key=func函数名,函数接收的参数是前面给定的可迭代对象一个一个放进去比较。例:

dic_value(i):
    return i[1]
dic1 = {'laura' : 80, 'wendy' : 18, 'iris' : 50}
print(min(dic1.items(), key=dic_value))  # key 接收的是字典里面的值。

运行结果

('wendy', 18)

(2) divmod(a,b)两个非复数参数,返回一对数字,他们的商和余数。integer division, 结果相当于(a//b, a%b),例:

print(divmod(89, 9))
print(divmod(65, 8))

运行结果:

(9, 8)
(8, 1)

(4) abs(x)
返回一个绝对值,参数可以是整数或者一个浮点数.例

print(abs(-98.78))

结果

98.78

(5) all(iterable)
返回True 如果所有可迭代的元素都符合给定的条件,如

print(all([4, 6, 3, 5]))
print(all(['i', '9', '0', 0]))
print(all([]))
print(all(()))

结果

True
False
True
True

(10)locals() 返回当前局部变量的值

def func(a):
    c = 1
    print(locals())
    print(globals())
func(3)

结果

{'a': 3, 'c': 1}  # 这个是局部变量
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001FC9C4D5438>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/学习资料/Code for everyday/day 13.py', '__cached__': None, 'func': <function func at 0x000001FC9C46D1E0>}

(11)print(self, *args, sep=’ ‘, end=’\n’, file=None)

1, 333, 344, sep='*')
print(333, end='\t')
print(222)
f = open('log','w',encoding='utf-8')
print('写入文件', file

结果

111*333*344
333	222

(12)callable(object) 返回object是否可被调用。

print(callable(0))
print(callable('runoob'))
def add(a, b):
    return a + b
print(callable(add))

结果

False
False
True

(13)encode

s = '你好'
bs = s.encode('utf-8')  # 把s从unicode编码方式转换成utf-8的编码方式,
print(bs)
s1 = bs.decode('utf-8') # 解码成unicode编码
print(s1)

结果

b'\xe4\xbd\xa0\xe5\xa5\xbd' # 中文一个字符占三个字节
你好

(14)repr(object) 返回字符串本来的样子

name = 'laura'
print("I'm %r" % name)
repr

结果

I'm 'laura'

(15) dir(obj)
dir(obj)
返回一个字符串列表, 如果没有传参,返回当前范围的变量名,也就是当前所在的命名空间。否则,返回一个按字母排序的列表在给定的参数的空间中。如果在方法中被命名为__dir__,dir()可触发__dir__下的代码块,否则,默认情况下:
当参数是一个模块对象时(如文件):返回模块的所有属性
当参数是一个类对象时:返回类的属性,和继承的类的所有属性
其他对象:自己的属性,类属性,父类属性。


def dir(p_object=None): # real signature unknown; restored from __doc__
    """
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.
    """
    return []

import os


class A:
    a = 1
    def func(self):
        print('func')
        
    @classmethod
    def func2(cls):
        print('func2')
        
    @staticmethod
    def func3():
        print('func3')
        
	def __dir__(self):
        print('dir')
        
aa = A()
print(dir(aa)) # dir    
print(dir(A))  # 类A中的属性,返回父类object中的所有属性和A类自己的属性 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'func', 'func2', 'func3']

print(dir())  # 本文件的属性  ['A', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'os']

print(dir(os))  # 导入的模块的属性

运行结果

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'func', 'func2', 'func3']
['A', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'os']
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']

(16) dict
A dictionary or other mapping object used to store an object’s (writable) attributes.
返回另外一个映射对象储存了对象的属性(可写的)
dict = {}

class A:
    a = 1
    def func(self):
        print('func')
    @classmethod
    def func2(cls):
        print('func2')
    @staticmethod
    def func3():
        print('func3')

    def __dir__(self):
        print('dir')

print(A.__dict__)
print(aa.__dict__)

运行结果

{'__module__': '__main__', 'a': 1, 'func': <function A.func at 0x0000029F4A86CD90>, 'func2': <classmethod object at 0x0000029F4A88BDA0>, 'func3': <staticmethod object at 0x0000029F4A88BDD8>, '__dir__': <function A.__dir__ at 0x0000029F4A86CE18>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
{}

  • locals() 返回当前名称空间所有变量
    在这里插入图片描述
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值