pythoninscope
㈠ 如何在python中获取完整的异颜桓
我们可以很容易的通过Python解释器获取帮助。如果想知道一个对象(object)更多的信息,那么可以调用help(object)!另外还有一些有用的方法,dir(object)会显示该对象的大部分相关属性名,还有object._doc_会显示其相对应的文档字符串。下面对其进行逐一介绍。
1、 help()
help函数是Python的一个内置函数。
函数原型:help([object])。
可以帮助我们了解该对象的更多信息。
Ifno argument is given, the interactive help system starts on the interpreter console.
>>> help()
Welcome to Python 2.7! This is the online help utility.
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at .
Enter the name of any mole, keyword, or topic to get help on writing
Python programs and using Python moles. To quit this help utility andreturn to the interpreter, just type "quit".
To get a list of available moles, keywords, or topics, type "moles","keywords", or "topics". Each mole also comes with a one-line summary
of what it does; to list the moles whose summaries contain a given word
such as "spam", type "moles spam".
help> int # 由于篇幅问题,此处只显示部分内容,下同Help on class int in mole __builtin__:class int(object)
| int(x=0) -> int or long
| int(x, base=10) -> int or long
|
.....help>
Ifthe argument is a string, then the string is looked up as the name of amole,function,class,method,keyword, ordocumentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
>>> help(abs) # 查看abs函数Help on built-in function abs in mole __builtin__:
abs(...)
abs(number) -> number
Return the absolute value of the argument.>>> help(math) # 查看math模块,此处只显示部分内容Help on built-in mole math:
NAME
math
FILE
(built-in)
DESCRIPTION
This mole is always available. It provides access to the
mathematical functions defined by the C standard.
FUNCTIONS
acos(...)
acos(x)
Return the arc cosine (measured in radians) of x.
.....>>> 293031
2、dir()
dir函数是Python的一个内置函数。
函数原型:dir([object])
可以帮助我们获取该对象的大部分相关属性。
Without arguments, return the list of names in the current local scope.
>>> dir() # 没有参数['__builtins__', '__doc__', '__name__', '__package__']>>> >>> import math # 引入一个包和一个变量,再次dir()>>> a=3>>> >>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'math']>>> 12345678910
With an argument, attempt to return a list of valid attributes for that object.
>>> import math>>> dir(math) # math模块作为参数['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'sign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']>>> 12345
The default dir() mechanism behaves differently with different types of objects, as it attempts to proce the most relevant, rather than complete, information:
• If the object is a mole object, the list contains the names of the mole’s attributes.
>>> import math>>> dir(math) # math模块作为参数['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'sign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']>>> 12345
• If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
>>> dir(float) # 类型['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__rece__', '__rece_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']>>> dir(3.4)
['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__rece__', '__rece_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']>>> >>> class A:
x=3
y=4>>> class B(A):
z=5>>> dir(B) # 类['__doc__', '__mole__', 'x', 'y', 'z']>>> 123456789101112131415161718
• Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
3、_doc_
在Python中有一个奇妙的特性,文档字符串,又称为DocStrings。
用它可以为我们的模块、类、函数等添加说明性的文字,使程序易读易懂,更重要的是可以通过Python自带的标准方法将这些描述性文字信息输出。
上面提到的自带的标准方法就是_doc_。前后各两个下划线。
注:当不是函数、方法、模块等调用doc时,而是具体对象调用时,会显示此对象从属的类型的构造函数的文档字符串。
>>> import math>>> math.__doc__ # 模块'This mole is always available. It provides access to the
mathematical functions defined by the C standard.'>>> abs.__doc__ # 内置函数'abs(number) -> number
Return the absolute value of the argument.'>>> def addxy(x,y):
'''the sum of x and y'''
return x+y>>> addxy.__doc__ # 自定义函数'the sum of x and y'>>> a=[1,2,4]>>> a.count.__doc__ # 方法'L.count(value) -> integer -- return number of occurrences of value'>>> b=3>>> b.__doc__ # 具体的对象"int(x=0) -> int or long
int(x, base=10) -> int or long
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead.
If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4">>> 12345678910111213141516171819
其实我们可以通过一定的手段来查看这些文档字符串,比如使用Pycharm,在对应的模块、函数、方法等上鼠标“右击”->Go to->Declaration。例如:查看内置函数abs的文档字符串
参考文献:
1、Python帮助文档
㈡ python中如何在函数中把字符串中的global语句执行
[root@-xlPythonTest]#vimstu.py
#!/usr/bin/python
#coding=utf-8
scope={}
defaddstu():
code=raw_input('请输入学生的学号')
exec('d'+code+'='+code)inscope
printscope['d'+code]
addstu()
[root@-xlPythonTest]#pythonstu.py
请输入学生的学号123
123
法二:传参数也行
#!/usr/bin/python
#coding=utf-8
defaddstu(scope):
code=raw_input('请输入学生的学号:')
scope['d'+code]=code
printscope['d'+code]
scope={}
addstu(scope)
printscope
[root@-xlPythonTest]#pythonstu.py
请输入学生的学号:456
456
{'d456':'456'}
㈢ python中 *= 是什么意思
1、两个值相加,然后返回值给符号左侧的变量
举例如下:
>>> a=1
>>> b=3
>>> a+=b(或者a+=3)
>>> a
4
2、用于字符串连接(变量值带引号,数据类型为字符串)
>>> a='1'
>>> b='2'
>>> a+=b
>>> a
'12'

8、运算符优先级
以下所列优先级顺序按照从低到高优先级的顺序;同行为相同优先级。
Lambda #运算优先级最低
逻辑运算符: or
逻辑运算符: and
逻辑运算符:not
成员测试: in, not in
同一性测试: is, is not
比较: <,<=,>,>=,!=,==
按位或: |
按位异或: ^
按位与: &
移位: << ,>>
加法与减法: + ,-
乘法、除法与取余: *, / ,%
正负号: +x,-x
具有相同优先级的运算符将从左至右的方式依次进行,用小括号()可以改变运算顺序。
参考资料来源:网络-Python
㈣ python基础教程 10-11例子如何执行
2020年最新Python零基础教程(高清视频)网络网盘
链接:
若资源有问题欢迎追问~

㈤ python中的for in的相关问题
A.因为已经引入了sqrt函数,如果在自己的空间中执行 sqrt=1 '把sqrt当成了一个变量,再运行sqrt(4)会出错
例子中 exec运行代码 在Scope空间中 sqrt是个变量,赋值1,如果没有in scope,那么exce运行空间就是本空间,再次sqrt(4)就会出错。
对比:
a=1234
exec 'a=4321'
a
4321
和代码:
a=1234
b={}
exec 'a=4321' in b
a
1234
B:print [x*x for x in range(10) if x % 3 == 0]
这里range(10)产生0,1,2~8,9 这10个数字
后面添加了条件x % 3 ==0,就是判断 x除以3的余数 等于0, 筛选出0、3、6、9
传递给x*x,就产生了一个列表:[0,9,36,81]
㈥ python编程问题
错误:
复制代码代码如下:
>>> def f(x, y):
print x, y
>>> t = ('a', 'b')
>>> f(t)
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <mole>
f(t)
TypeError: f() takes exactly 2 arguments (1 given)
【错误分析】不要误以为元祖里有两个参数,将元祖传进去就可以了,实际上元祖作为一个整体只是一个参数,
实际需要两个参数,所以报错。必需再传一个参数方可.
复制代码代码如下:
>>> f(t, 'var2')
('a', 'b') var2
更常用的用法: 在前面加*,代表引用元祖
复制代码代码如下:
>>> f(*t)
'a', 'b'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> def func(y=2, x):
return x + y
SyntaxError: non-default argument follows default argument
【错误分析】在C++,Python中默认参数从左往右防止,而不是相反。这可能跟参数进栈顺序有关。
复制代码代码如下:
>>> def func(x, y=2):
return x + y
>>> func(1)
3
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> D1 = {'x':1, 'y':2}
>>> D1['x']
1
>>> D1['z']
Traceback (most recent call last):
File "<pyshell#185>", line 1, in <mole>
D1['z']
KeyError: 'z'
【错误分析】这是Python中字典键错误的提示,如果想让程序继续运行,可以用字典中的get方法,如果键存在,则获取该键对应的值,不存在的,返回None,也可打印提示信息.
复制代码代码如下:
>>> D1.get('z', 'Key Not Exist!')
'Key Not Exist!'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> from math import sqrt
>>> exec "sqrt = 1"
>>> sqrt(4)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <mole>
sqrt(4)
TypeError: 'int' object is not callable
【错误分析】exec语句最有用的地方在于动态地创建代码字符串,但里面存在的潜在的风险,它会执行其他地方的字符串,在CGI中更是如此!比如例子中的sqrt = 1,从而改变了当前的命名空间,从math模块中导入的sqrt不再和函数名绑定而是成为了一个整数。要避免这种情况,可以通过增加in <scope>,其中<scope>就是起到放置代码字符串命名空间的字典。
复制代码代码如下:
>>> from math import sqrt
>>> scope = {}
>>> exec "sqrt = 1" in scope
>>> sqrt(4)
2.0
㈦ python函数
参数match是正则表达式匹配后的结果,match.group(1)就是返回结果1。
importre
m=re.search('(^.+?) (.+?$)','print"111" print"222"')
printm.group(1)#print"111"
eval()一般是用来执行字符串代码,也就是命令注入。
其中的参数code:就是要执行的代码,比如print "111"
其中的参数scope:是code执行范围的字典.
由于匹配的字符串代码经常有格式对齐等问题,所以加一个try except来捕捉。
exec跟eval类似,可以执行代码,但是只是一个语法,没有返回值。
exec code in scope就是执行code作用范围为scope字典
㈧ Python3 exec函数 scope失效 exec('sqrt = 1' in scope)
是exec('sqrt = 1' )in scope
python3下应该是:
exec('sqrt = 1' , scope)
