[英]Passing default arguments to functions in Python
新手在這里,所以請溫柔。 我正在使用網格物體,我有一組不可變列表(元組),它們包含原始輸入網格的屬性。 這些列表以及原始網格用作組織指南,以便密切關注新創建的子網格; 即,由於子網格引用原始網格,其屬性(列表)可用於在子網格之間進行引用,或創建子網格的子網格。 貝婁列出了其中一些列表的結構:
vertices = [ (coordinate of vertex 1), ... ]
faceNormals = [ (components of normal of face 1), ...]
faceCenters = [ (coordinates of barycenter of face 1), ...]
因為我不熟悉oop,所以我組織了我的腳本:
def main():
meshAttributes = GetMeshAttributes()
KMeans(meshAttributes, number_submeshes, number_cycles)
def GetMeshAttributes()
def Kmeans():
func1
func2
...
def func1()
def func2()
...
main()
問題是在KMeans中的每個函數中,我必須將一些網格的屬性作為參數傳遞,並且我不能默認它們,因為它們在腳本的開頭是未知的。 例如,Kmeans內部是一個名為CreateSeeds的函數:
def CreateSeeds(mesh, number_submeshes, faceCount, vertices, faceVertexIndexes):
最后三個參數是靜態的,但我做不了類似的事情:
CreateSeeds(mesh, number_submeshes)
因為我必須在函數定義中放置faceCount, vertices, faceVertexIndexes
,並且這些列表在開頭是巨大且未知的。
我嘗試過使用類,但是由於我對它們的了解有限,我遇到了同樣的問題。 有人可以給我一些關於在哪里查找解決方案的建議嗎?
謝謝!
你想要的是獲得一個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
如果要指定最后一個參數,可以使用關鍵字參數或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.