擅长:python、mysql、java
<p>在python中,函数也是对象,可以传递。您的代码中有一个小错误,并且有一个简单的方法来简化它。你知道吗</p>
<p>第一个问题是调用函数<code>foo</code>,同时将其传递给<code>Button</code>类。这将把<code>foo()</code>的结果传递给类,而不是函数本身。我们只想传递<code>foo</code>。你知道吗</p>
<p>我们可以做的第二件好事就是将函数赋给一个名为function(或者executeFunction)的实例变量,然后可以通过<code>newButton.function()</code>调用它。你知道吗</p>
<pre><code>def foo():
print "bar"
class Button(object):
def __init__(self, name, color, function):
self.name = name
self.color = color
self.function = function
newButton = Button("Example", red, foo)
newButton.function()
</code></pre>