gpt4 book ai didi

python - 艰难地学习 Python : Exercise 43 Function Creation

转载 作者:太空宇宙 更新时间:2023-11-03 14:29:38 25 4
gpt4 key购买 nike

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() 的函数) .

如有任何帮助,我们将不胜感激!

最佳答案

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>

关于python - 艰难地学习 Python : Exercise 43 Function Creation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13773138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com