有没有办法在跳过列表中的1个指定函数的同时从另一个方法运行方法中的函数列表?
例如,我有contentList方法:
def contentList(self):
methods = [self.title, self.containerDIV, self.heading, self.stopSection, self.offlineSection, self.onlineSection, self.endDIV, self.otherImages]
for m in methods:
m()
def test(self):
self.contentList()
# skip over stopSection
有没有办法在跳过或不运行self.stopSection时从测试方法运行这些方法?
更新
以下是我正在尝试的内容:
#**************************** BEGIN OF HTML CONTENT ****************************
def title(self):
self.wfile.write(bytes("<div id='title'><img src='../images/title.png'></div>", "utf8"))
def containerDIV(self):
self.wfile.write(bytes("<div id='container'", "utf8"))
def endDIV(self):
self.wfile.write(bytes("</div>", "utf8"))
#**************************** END OF HTML CONTENT ****************************
def contentList(self, skip_name): # All content functions in list
methods = [self.title, self.containerDIV, self.endDIV]
for m in methods:
if m.__name__ != skip_name:
m()
def narrow(self):
try:
self.contentList('title') # removed title
return
# GET
def do_GET(self):
try:
self.contentList('none') # I added none here because I want to keep title
return
答案 0 :(得分:1)
根据您的范围,您可以在执行之前临时更改函数的定义。
全球范围
def t1():
print('t1')
def t2():
print('t2')
def contentList():
methods = [t1, t2]
for m in methods:
m()
def test():
global t1
def fake(): pass
temp = t1
t1 = fake
contentList()
t1 = temp
test()
班级范围
def test(self):
def fake(): pass
temp = self.stopSection
self.stopSection = fake
self.contentList()
self.stopSection = temp
答案 1 :(得分:1)
您可以通过__name__
属性检查功能名称。因此,在您的情况下,您可以执行以下操作:
class SomeClass:
def contentList(self, skip_method_name):
methods = [self.title, self.containerDIV, self.heading, self.stopSection, self.offlineSection, self.onlineSection, self.endDIV, self.otherImages]
for m in methods:
if m.__name__ != skip_method_name:
m()
def test(self):
self.contentList('stopSection')
让我提供一个更简洁的例子
class SomeClass:
def method_a(self):
print('method_a')
def method_b(self):
print('method_b')
def method_runner(self, skip_name):
for m in [self.method_a, self.method_b]:
if m.__name__ != skip_name:
m()
样本用法:
>>> some_obj = SomeClass()
>>> some_obj.method_runner('')
method_a
method_b
>>> some_obj.method_runner('method_a')
method_b
>>> some_obj.method_runner('method_b')
method_a
正如@Jeronimo所指出的那样,我们可以使用method_runner
方法中的实际函数并完全绕过__name__
调用。使用这个方法我的例子如下:
class SomeClass:
def method_a(self):
print('method_a')
def method_b(self):
print('method_b')
def method_runner(self, skip_method):
for m in [self.method_a, self.method_b]:
if m != skip_method:
m()
示例用法:
>>> some_obj = SomeClass()
>>> some_obj.method_runner(None)
method_a
method_b
>>> some_obj.method_runner(some_obj.method_a)
method_b
>>> some_obj.method_runner(some_obj.method_b)
method_a