我正在研究Python的基础知识,并测试了解释器中的一些内置函数。我正在查看的文档正在谈论Python 3 ...我正在使用Python 2.7.3。
>>> x = '32456'
>>> x
'32456'
>>> isalpha(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'isalpha' is not defined
我做了一些研究,似乎并不仅isalpha()
限于Python3。sin(3.3)
即使这样做,我也无法使用import math
那么,为什么我会看到一个错误?为了使这些功能正常工作,我还需要导入其他模块吗?
isalpha()
不是函数,而是str
类型的方法。如果需要,可以将其提取为未绑定的方法,并以函数名称命名:
>>> "hello".isalpha()
True
>>> "31337".isalpha()
False
>>> isalpha = str.isalpha
>>> isalpha("hello")
True
>>> isalpha("31337")
False
导入模块中的功能是该模块的成员。要将函数拉入主名称空间,请使用以下from
语句:
>>> import math
>>> math.sin(3.3)
-0.1577456941432482
>>> from math import cos
>>> cos(3.3)
-0.9874797699088649
现在,为什么Python会这样工作?无论是math
模块和logging
模块有一个调用的函数log()
,但他们做的非常不同的事情。
>>> import math, logging
>>> help(math.log)
log(...)
log(x[, base])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
>>> help(logging.log)
log(level, msg, *args, **kwargs)
Log 'msg % args' with the integer severity 'level' on the root logger. If
the logger has no handlers, call basicConfig() to add a console handler
with a pre-defined format.
如果所有导入的符号都像您执行操作时那样直接进入主命名空间from math import *
,则程序将无法使用这两个模块的log()
功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句