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

时间:2012-12-08 00:25:57

标签: python getattr

while True:
    print "\n--------"
    room = getattr(self, next)
    next = room()

我的问题源于Learn Python The Hard Way - Exercise 43中的上述代码块。我理解第三行将getattr()函数结果(在本例中为self.next)存储到room变量中(除非我错了......?)

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

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:5)

room = getattr(self, next)

返回函数,然后可以调用。

next = room()

函数是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>
相关问题