栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python:函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python:函数

1 函数

Python的函数可以分为内置函数、模块函数和用户自定义函数三类。
(1)用户自定义函数可以写在单行函数,称为“lambda函数”。
(2)用户自定义函数可以放在“类(class)”中,也可以放在类外。原因在于,Python不仅支持面向对象编程,还支持面向过程编程。

1.1 内置函数

内置函数(Built- In Function,BIF)是指已内置在Python解释器中的函数,其调用方法为“直接用函数名”。

i = 20
type(i)

int

1.2 模块函数

模块函数是指定义在Python模块中的函数,其调用方法为“先import所属模块,后通过‘模块名’或‘模块别名’调用”。

import math as mt
mt.sin(1.5)

0.9974949866040544

sin(1.5)

NameError Traceback (most recent call last)
in
----> 1 sin(1.5)

NameError: name ‘sin’ is not defined

1.3 用户自定义函数

“用户自定义函数”是指用户自己定义的函数,其调用方法为“直接用函数名”。

  • 用关键字def定义“用户自定义函数”。
def myFunc():
    j = 0
    print('hello world')
myFunc()

hello world

  • 在Python中,用户自定义函数可以写成“单行函数”,称为“lambda函数”。
  • Python既支持面向对象编程,又支持面向过程编程。因此,用户自定义函数可以放在类(class)中,也可以放在类外。前者称为“方法”,后者称为“函数”。初学者要区分“函数”和“方法”的概念。
2 内置函数 2.1 内置函数的主要特点
  • 内置函数(BIF)的主要特点是“直接通过函数名调用”。
  • 在Python中,“函数”与“方法”是两个不同的概念。
  • Python内置函数的源代码不一定是Python代码。
  • 查看内置函数的方法——内置函数dir()。
dir(__builtins__)

​Out:

['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'baseException',
 'BlockingIOError',
 'BrokenPipeError',
 'BufferError',
 'BytesWarning',
 'ChildProcessError',
 'ConnectionAbortedError',
 'ConnectionError',
 'ConnectionRefusedError',
 'ConnectionResetError',
 'DeprecationWarning',
 'EOFError',
 'Ellipsis',
 'EnvironmentError',
 'Exception',
 'False',
 'FileExistsError',
 'FileNotFoundError',
 'FloatingPointError',
 'FutureWarning',
 'GeneratorExit',
 'IOError',
 'importError',
 'importWarning',
 'IndentationError',
 'IndexError',
 'InterruptedError',
 'IsADirectoryError',
 'KeyError',
 'KeyboardInterrupt',
 'LookupError',
 'MemoryError',
 'ModuleNotFoundError',
 'NameError',
 'None',
 'NotADirectoryError',
 'NotImplemented',
 'NotImplementedError',
 'OSError',
 'OverflowError',
 'PendingDeprecationWarning',
 'PermissionError',
 'ProcessLookupError',
 'RecursionError',
 'ReferenceError',
 'ResourceWarning',
 'RuntimeError',
 'RuntimeWarning',
 'StopAsyncIteration',
 'StopIteration',
 'SyntaxError',
 'SyntaxWarning',
 'SystemError',
 'SystemExit',
 'TabError',
 'TimeoutError',
 'True',
 'TypeError',
 'UnboundLocalError',
 'UnicodeDecodeError',
 'UnicodeEncodeError',
 'UnicodeError',
 'UnicodeTranslateError',
 'UnicodeWarning',
 'UserWarning',
 'ValueError',
 'Warning',
 'WindowsError',
 'ZeroDivisionError',
 '__IPYTHON__',
 '__build_class__',
 '__debug__',
 '__doc__',
 '__import__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'abs',
 'all',
 'any',
 'ascii',
 'bin',
 'bool',
 'breakpoint',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'display',
 'divmod',
 'enumerate',
 'eval',
 'exec',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'repr',
 'reversed',
 'round',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'vars',
 'zip']
2.2 数学函数
# 求绝对值
abs(-1)

1

# 求最小值
min([1,2,3])

1

# 求最大值
max([1,2,3])

3

# 求2的10次方
pow(2,10)

1024

# 四舍五入,第二个参数的含义为小数点之后保留的有效位数
round(2.991,2)

2.99

2.3 类型函数
# 强制类型转换为int(整数):int()
int(1.134)

1

# 强制类型转换为bool(布尔值):bool()
bool(1)

True

# 强制类型转换为float(浮点数):float()
float(1)

1.0

# 强制类型转换为str(字符串):str()
str(123)

‘123’

# 强制类型转换为list(列表):list()
list("chao")

[‘c’, ‘h’, ‘a’, ‘o’]

# 强制类型转换为set(集合):set()
set("chao")

{‘a’, ‘c’, ‘h’, ‘o’}

# 强制类型转换为tuple(元组):tuple()
tuple("chao")

(‘c’, ‘h’, ‘a’, ‘o’)

2.4 其他功能函数
# 查看数据类型:type()
i = 0
type(i)

int

# 判断数据类型:isinstance()
isinstance(i,int)

True

# 查看搜索路径:dir()
dir()

Out:

['In',
 'Out',
 '_',
 '_1',
 '_10',
 '_11',
 '_12',
 '_13',
 '_14',
 '_15',
 '_16',
 '_17',
 '_18',
 '_19',
 '_2',
 '_21',
 '_22',
 '_5',
 '_6',
 '_7',
 '_8',
 '_9',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i14',
 '_i15',
 '_i16',
 '_i17',
 '_i18',
 '_i19',
 '_i2',
 '_i20',
 '_i21',
 '_i22',
 '_i23',
 '_i3',
 '_i4',
 '_i5',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 'exit',
 'get_ipython',
 'i',
 'mt',
 'myFunc',
 'quit']
# 查看帮助:help()
help(dir)

Out:

Help on built-in function dir in module builtins:

dir(...)
    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.
# 快速生成序列:range()
range(1,10,2)  # range(1,10,2)用于生成一个迭代器

range(1, 10, 2)

list(range(1,10,2))

[1,3,5,7,9]
range()的返回值为一个迭代器,迭代器是“惰性计算”的,所以通过强制类型转换函数list()将迭代器的值进行计算并显示。

# 判断函数可否被调用:callable()
callable(dir)

True

# 十进制转换为二进制:bin()
bin(8)

‘0b1000’

# 十进制转换为十六进制:hex()
hex(8)

‘0x8’

3 模块函数

与“内置函数”不同的是,“模块函数”的定义在第三方提供的包或模块之中,其调用必须在“导入模块”的前提下进行,并通常通过模块名调用。

3.1 import 模块名
  • 第一种导入方法:
    import 模块名
  • 在此方法中函数的调用方法:
    模块名.函数名()
import math
math.sin(1.5)

0.9974949866040544

3.2 import 模块名 as 别名
  • 第二种导入方法:
    import 模块名 as 别名
  • 从原理上看,“import 模块名 as 别名”中的“别名”用户可以自行定义。但是,在数据分析和数据科学实践中,为了保证源代码的可读性,每个包或模块的“别名”并不是随意给出的,而是采用约定俗成的“别名”,如pandas、numpy的“别名”一般为pd和np。
  • 在此方法中,函数的调用:
    别名.函数名()
import math as mt
mt.sin(1.5)

0.9974949866040544

3.3 from 模块名 import 函数名
  • 第三种导入方法:
    from 模块名 import 函数名
  • 用此方法导入的模块中的函数的调用方法:
    函数名()
from math import cos
cos(1.5)

0.0707372016677029

4 自定义函数
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/290899.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号