将成员函数作为函数参数传递?

2024-09-28 13:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为SQLite编写了一个非常简单的select函数,但是我对如何传递成员函数感到困惑。。。e、 g.:.fetchone().fetchmany()。在

def select(cursor, select="*", table="reuters", fetch=".fetchone()", tologfile=False, logfile=""):
    if tologfile:
        logfile = open(logfile, 'w')
        logfile.write(str(cursor.execute("select * from ?;".replace('?',table).replace("select * ", "select "+select)).fetchone()))
        logfile.close()
    else: return str(cursor.execute("select * from ?;".replace('?',table).replace("select * ", "select "+select)).fetchone())

如何将此成员函数作为参数传递?


Tags: 函数fromexecutesqlitedeftable成员select
3条回答

您只需传递self.fetchone来传递该函数。在

如果您希望它作为默认值,只需在函数定义中使用None,然后添加

if whatever is None:
    whatever = self.fetchone

在函数本身中。在

如果您想在另一个对象上调用该方法,但self将其作为字符串传递并使用以下代码(基于您的else代码,因为该代码较短):

^{pr2}$

lambda可以做到这一点

class A:
  def test(self):
    print "hello world"

a = A()
func = (lambda: a.test())
func()

打印“你好世界”

此技术还可以扩展到处理传递和转换参数

^{pr2}$

打印“foo”

您可以使用getattr:

>>> class A:
...     def b(self):
...             print 'c'
... 
>>> a = A()
>>> getattr(a,'b')
<bound method A.b of <__main__.A instance at 0x7f2a24a85170>>
>>> getattr(a,'b')()
c

相关问题 更多 >

    热门问题