函数内部赋值创建的变量在( A .内置作用域
C .函数嵌套作用域
应该选什么Python,为什么为什么”
在Python中,函数内部赋值创建的变量默认是在局部作用域(Local scope)中。这意味着这个变量只能在创建它的函数内部被访问和修改。
这是因为Python的作用域规则,也被称为LEGB规则,按照以下顺序查找变量:
所以,对于你的问题,函数内部赋值创建的变量应该是在局部作用域(Local scope)。如果你想在函数外部访问这个变量,你需要使用global
关键字或者nonlocal
关键字,或者通过返回值的方式来获取这个变量的值。
直接上 Python 代码,很短的(import 语句就不用写了吧,读者自行发挥就好):
test_struct = PyTestStruct()
test_struct.integer = 1
test_struct.c_str = 'Hello, C'.encode() # Python 2.x 则不需要写 encode
test_struct.ptr = 0xFFFFFFFF
test_struct.array = INTARRAY8()
for i in range(0, len(test_struct.array)):
j = i + 1
test_struct.array[i] = j * 10 + j
so_file = testdll()
test_result = so_file.print_test_struct(test_struct)
print('test_result:', test_result)
执行结果:
C -- {
C -- integer : 1
C -- cstr : Hello, C
C -- ptr : 0xffffffff
C -- array : [11, 22, 33, 44, 55, 66, 77, 88]
C -- }
test_result: success
这里可以看到,结构体参数的准备还是很简单的,就是将用 Python 适配过来之后的类中对应名字的成员进行赋值就好了。
注意一下在 Python 3.x 中,str
和 bytes
类型是区分开的,而 char *
对应的是后者,因此需要进行 encode / decode 转换。在 Python 2.x 则不需要。