简体   繁体   English

将默认参数传递给Python中的函数

[英]Passing default arguments to functions in Python

Newbie here, so please be gentle. 新手在这里,所以请温柔。 I am working with meshes and I have a set of immutable lists (tuples) which contain the attributes of an original input mesh. 我正在使用网格物体,我有一组不可变列表(元组),它们包含原始输入网格的属性。 These lists, as well as the original mesh, are used as an organizational guide to keep tabs on newly created submeshes; 这些列表以及原始网格用作组织指南,以便密切关注新创建的子网格; ie since the submeshes reference the original mesh, its attributes (the lists) can be used to reference between submeshes, or to create submeshes of submeshes. 即,由于子网格引用原始网格,其属性(列表)可用于在子网格之间进行引用,或创建子网格的子网格。 Bellow are listed the structure of some of these lists: 贝娄列出了其中一些列表的结构:

vertices = [ (coordinate of vertex 1), ... ]
faceNormals = [ (components of normal of face 1), ...]
faceCenters = [ (coordinates of barycenter of face 1), ...]

Since I am not acquainted with oop, I have organized my script like so: 因为我不熟悉oop,所以我组织了我的脚本:

def main():
    meshAttributes = GetMeshAttributes()
    KMeans(meshAttributes, number_submeshes, number_cycles)

def GetMeshAttributes()
def Kmeans():
    func1
    func2
    ...
def func1()
def func2()
...
main()

The problem is that on every function inside KMeans, I have to pass some of the mesh's attributes as arguments, and I can't default them because they are unknown at the beginning of the script. 问题是在KMeans中的每个函数中,我必须将一些网格的属性作为参数传递,并且我不能默认它们,因为它们在脚本的开头是未知的。 For example inside Kmeans is a function called CreateSeeds: 例如,Kmeans内部是一个名为CreateSeeds的函数:

def CreateSeeds(mesh, number_submeshes, faceCount, vertices, faceVertexIndexes):

The last three arguments are static, but I can't do something like: 最后三个参数是静态的,但我做不了类似的事情:

CreateSeeds(mesh, number_submeshes)

because I would have to place faceCount, vertices, faceVertexIndexes inside the function definition, and these list are huge and unknown at the beginning. 因为我必须在函数定义中放置faceCount, vertices, faceVertexIndexes ,并且这些列表在开头是巨大且未知的。

I have tried using classes, but in my limited knowledge of them, I had the same problem. 我尝试过使用类,但是由于我对它们的了解有限,我遇到了同样的问题。 Could someone give me some pointers on where to look up a solution? 有人可以给我一些关于在哪里查找解决方案的建议吗?

Thanks! 谢谢!

What you want is to obtain a partial function application: 你想要的是获得一个partial功能应用程序:

>>> from functools import partial
>>> def my_function(a, b, c, d, e, f):
...     print(a, b, c, d, e, f)
... 
>>> new_func = partial(my_function, 1, 2, 3)
>>> new_func('d', 'e', 'f')
1 2 3 d e f

If you want to specify the last parameters you can either use keyword arguments or a lambda : 如果要指定最后一个参数,可以使用关键字参数或lambda

>>> new_func = partial(my_function, d=1, e=2, f=3)
>>> new_func('a', 'b', 'c')
a b c 1 2 3
>>> new_func = lambda a,b,c: my_function(a, b, c, 1, 2, 3)
>>> new_func('a', 'b', 'c')
a b c 1 2 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM