学习Python艰难的方法:练习43功能创建

Arc*_*rc' 3 python getattr

while True:
    print "\n--------"
    room = getattr(self, next)
    next = room()
Run Code Online (Sandbox Code Playgroud)

我的问题源于上面的代码块,可以在Learn Python The Hard Way中找到 - 练习43.据我所知,第三行将getattr()函数结果(在本例中为self.next)存储到room变量中(除非我错了......?)

现在让我感到兴奋的是第四行,其中函数room()存储在变量中next.从根本上说,我不理解该room()部分,因为这不是代码块中定义的函数.Python是否允许用户根据前面的变量定义函数?(例如:room()第一次写入会创建一个room()基于变量中存储的函数调用的函数room).

任何帮助将不胜感激!

Aes*_*ete 5

room = getattr(self, next)
Run Code Online (Sandbox Code Playgroud)

返回一个函数,然后可以调用它.

next = room()
Run Code Online (Sandbox Code Playgroud)

函数是python中的第一类对象,因此它们可以这样传递.便利!

考虑以下:

>>> class foo:
      def bar(self):
        print 'baz!'
      def __init__(self):
        # Following lines do the same thing!
        getattr(self, 'bar')()
        self.bar() 
>>> foo()
baz!
baz!
<__main__.foo instance at 0x02ADD8C8>
Run Code Online (Sandbox Code Playgroud)