-
Notifications
You must be signed in to change notification settings - Fork 960
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2.编写条件分支代码的技巧 #18
Comments
这样肯定是不行的。在python中函数也是一种对象,它能被赋值给变量,故调用该变量就是执行该函数。感觉你对这个理解有些不清晰,具体可以看廖雪峰的教程开头的例子。作者在这里是巧妙地通过给同一个变量赋予不同的值来执行了不同的函数 |
感谢帮忙解答,先 close 了 :) |
我理解的是:把函数赋值给变量,应该是 变量=函数名,如果是 函数名=变量,而变量之前并没有被定义,那不就报错了吗? |
你的理解没有错,只是对代码可能有误解, |
我在 Jupyter 里运行了一下, |
扩展了一下原文里的代码,这样可能更容易理解一些。 只有 def now():
return 100
def create_user_profile(username, email, age, address, points, created):
""" code to create a new user profile """
print("creating user")
def update_user_profile(username, email, age, address, updated):
""" code to update a existing user profile """
print("updating user")
if True:
profile_func = create_user_profile
extra_args = {'points': 0, 'created': now()}
else:
profile_func = update_user_profile
extra_args = {'updated': now()}
# either create or update a user profile, no matter it already exists or not
profile_func(
username='user.username',
email='user.email',
age='user.age',
address='user.address',
**extra_args
) 如果在你标出的位置使用 我在Jupyter里面也运行了,的确不会报错,但是也的确没有按照期望调用到相应的函数。原因是Jupyter的执行环境有上下文的,如果你先运行了正确的代码,再执行你的代码,实际上 贴了我测试的代码,你可以尝试在你想要修改的地方修改再运行试试,注意,我直接用了True/False来控制调用哪个函数,意思差不多。最好别用Jupyter,问题就很明确了。 |
谢谢,明白了 |
你好,上面代码中我标记了 “+++” 的两行可以改成下面这样的吗?
The text was updated successfully, but these errors were encountered: