[英]A python function that return a list of function with a for loop
我正在嘗試實現一個 function (make_q),它返回使用 make_q 獲取的參數 (P) 生成的函數 (Q) 列表。 Q 是一個依賴於 n(=len(P)) 的變量,並且使 Q 函數相似,因此可以在 for 循環中完成,但如果我在循環中將 function 命名為,它們都將具有相同的地址,所以我只得到最后一個 Q,有沒有繞過這個? 這是我的代碼,
def make_q(self):
Temp_P=[p for p in self.P]
Q=()
for i in range(self.n-1):
p=min(Temp_P)
q=max(Temp_P)
index_p=Temp_P.index(p)
index_q=Temp_P.index(q)
def tempQ():
condition=random.random()
if condition<=(p*self.n):
return index_p
else:
return index_q
Temp_Q=list(Q)
Temp_Q.append(tempQ)
Q=tuple(Temp_Q)
q-=(1-p*self.n)/self.n
Temp_P[index_q]=q
Temp_P.pop(index_p)
return Q
test.Q
(<function __main__.Test.make_q.<locals>.tempQ()>,
<function __main__.Test.make_q.<locals>.tempQ()>,
<function __main__.Test.make_q.<locals>.tempQ()>,
<function __main__.Test.make_q.<locals>.tempQ()>,
<function __main__.Test.make_q.<locals>.tempQ()>)
我還嘗試將它們設為元組,以便它們具有不同的地址,但它不起作用。 有沒有辦法像tempQi
一樣dynamic
命名函數(tempQ)
jasonharper 在評論中的觀察和解決方案是正確的(應該是公認的答案)。 但既然你問到元類,我還是把這個貼出來。
在 python 中,每個 class 都是一個type
,有“name”、“bases”(基類)和“attrs”(類的所有成員)。 本質上,元類定義了 class 的行為,您可以在https://www.python-course.eu/python3_metaclasses.ZE1BFD762321E409CEE4AC0B6E841963C和其他各種在線教程中了解更多信息。
__new__
方法在設置 class 時運行。 請注意attrs
的用法,其中您的 class 成員self.n
由attrs['n']
訪問(因為 attrs 是所有 class 成員的字典)。 我正在動態定義函數tempQ_0, tempQ_1...
如您所見,我們還可以將文檔字符串添加到這個動態定義的 class 成員中。
import random
class MyMetaClass(type):
def __new__(cls, name, bases, attrs):
Temp_P = [p for p in attrs['P']]
for i in range(attrs['n'] - 1):
p = min(Temp_P)
q = max(Temp_P)
index_p = Temp_P.index(p)
index_q = Temp_P.index(q)
def fget(self, index_p=index_p, index_q=index_q): # this is an unbound method
condition = random.random()
return index_p if condition <= (p * self.n) else index_q
attrs['tempQ_{}'.format(i)] = property(fget, doc="""
This function returns {} or {} randomly""".format(index_p, index_q))
q -= (1 - p * attrs['n']) / attrs['n']
Temp_P[index_q] = q
Temp_P.pop(index_p)
return super(MyMetaClass, cls).__new__(cls, name, bases, attrs)
# PY2
# class MyClass(object):
# __metaclass__ = MyMetaClass
# n = 3
# P = [3, 6, 8]
# PY3
class MyClass(metaclass=MyMetaClass):
n = 3
P = [3, 6, 8]
# or use with_metaclass from future.utils for both Py2 and Py3
# print(dir(MyClass))
print(MyClass.tempQ_0, MyClass.tempQ_1)
output
<property object at 0x10e5fbd18> <property object at 0x10eaad0e8>
所以你的函數列表是[MyClass.tempQ_0, MyClass.tempQ_1]
請嘗試通過格式化字符串,例如:“function_{}.format(name)”,您希望您的 output 看起來如何?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.