python3if语句_3种替代if语句的方法,使您的python代码更具可读性

阅读: 评论:0

python3if语句_3种替代if语句的⽅法,使您的python代码更具
可读性
python3if语句
Are you taking advantage of these features of Python that can help make your code make more sense?
您是否正在利⽤Python的这些功能来帮助使代码更有意义?
Code readability is not just about making your code shorter. It is about reducing the intellectual burden of understanding what your code is doing and how it is doing it.
代码的可读性不仅仅是使代码更短。 它是关于减轻理解代码正在做什么以及如何做的知识负担。
Some general rules of thumb are: explicit is better than implicit, clear is better than short, and don’t repeat yourself (DRY).
⼀些⼀般的经验法则是:显式胜于隐式,清晰胜于短,并且不要重复⾃⼰(DRY) 。
With that in mind, here are three (plus one bonus!) examples of situations where avoiding an if statement can help make your code more readable. They are:
考虑到这⼀点,下⾯是三个(加⼀加号!)避免使⽤if语句有助于提⾼代码可读性的⽰例。 他们是:
1. Testing for equality with more than one possible value
测试具有多个可能值的相等性
2. Selecting one value from a set of multiple possible values
从多个可能的值中选择⼀个值
3. Dynamically choosing one function to execute from a set of multiple possible functions (bonus: with custom
arguments)
从⼀组可能的功能中动态选择⼀个要执⾏的功能(奖⾦:带有⾃定义参数)
1.测试是否具有多个价值?⽤'in' ! (1. Testing for equality with more than one value? Use 'in’!) The n
ot-so-good way:
不太好的⽅法:
user_type = "regular"
if user_type == "admin" or user_type == "superadmin" or user_type == "moderator":
give_access()
The better way:
更好的⽅法:
user_type = "regular"
allowed_user_types = ["admin", "superadmin", "moderator"]
文山学院
if user_type in allowed_user_types:
give_access()
Why it’s better:
为什么更好:
As the number of allowed values increases, the ‘not-so-good’ way will stretch your if statement out.
随着允许值数量的增加,“不太好”的⽅法将使您的if语句失效。
Want to change the allowed values? Simply modify the list.
是否要更改允许的值? 只需修改列表。
By assigning the list of allowed values to a variable, you can use it elsewhere in your code too. For example, it makes writing assertions a breeze:
通过将允许值列表分配给变量,您也可以在代码的其他地⽅使⽤它。 例如,它使编写断⾔变得轻⽽易举:
assert user_type in allowed_user_types, f"user_type must be one of: {', '.join(allowed_user_types)}"
#
2.您的if语句有很多“ elifs”吗?使⽤字典! (2. Got lots of ‘elifs’ for your if statement? Use a dictionary!)
The not-so-good way:
不太好的⽅法:
def show_info_about_item(chosen_item="phone"):
if chosen_item == "phone":
return "Handheld communication device"
elif chosen_item == "car":
return "Self-propelled ground vehicle"
elif chosen_item == "dinosaur":
return "Extinct lizard"
else:
return "No info available"
The better way:
更好的⽅法:
def show_info_about_item(chosen_item="phone"):
info_dict = {
"phone": "Handheld communication device",
"car": "Self-propelled ground vehicle",
"dinosaur": "Extinct lizard"
}
return (chosen_item, "No info available")
Why it’s better:
为什么更好:
As the number of allowed values increases, the ‘not-so-good’ way will stretch your if statement out.
随着允许值数量的增加,“不太好”的⽅法将使您的if语句失效。
Made another possible value? Just add it to the dictionary!
取得了另⼀个可能的价值? 只需将其添加到字典中即可!
Allowed values can be spotted at a glance and also possibly used elsewhere using info_dict.keys().
可以⼀⽬了然地到允许的值,也可以使⽤info_dict.keys()在其他地⽅使⽤允许的值。
3.想动态执⾏功能吗?再次使⽤字典! (3. Want to execute a function dynamically? Use a dictionary (again)!)北京周边一日游推荐
The not-so-good way:
不太好的⽅法:
def add_one(x):
return x + 1
def divide_by_two(x):
return x/2
def square(x):
return x**2
# The not-so-good way:
def perform_operation(x, chosen_operation="add_one"):
if chosen_operation == "add_one":
x = add_one(x)
elif chosen_operation == "divide_by_two":
x = divide_by_two(x)
elif chosen_operation == "square":
x = square(x)
else:
raise Exception("Invalid operation")
return x
The better way:
更好的⽅法:
def add_one(x):
return x + 1
def divide_by_two(x):
return x/2
def square(x):
return x**2
def invalid_op(x):
raise Exception("Invalid operation")
# The better way:
def perform_operation(x, chosen_operation="add_one"):
ops = {
"add_one": add_one,
"divide_by_two": divide_by_two,
"square": square
}
广州旅游十大必去景点>上海周边团建两日游
chosen_operation_function = (chosen_operation, invalid_op)
return chosen_operation_function(x)
Why it’s better:
为什么更好:
As the number of possible functions increases, the ‘not-so-good’ way will stretch your if statement out.
随着可能函数的数量增加,“不太好”的⽅式将使您的if语句失效。
Made another possible operation? Just add it to the dictionary!
进⾏了其他可能的操作? 只需将其添加到字典中即可!
Allowed operations can be spotted at a glance and also possibly used elsewhere using ops.keys().
允许的操作可以⼀⽬了然,也可以在其他地⽅使⽤ops.keys() 。
奖励:带有⾃定义参数的动态函数 (Bonus: Dynamic functions with custom arguments)
What about if each of the possible functions has its own set of arguments?
如果每个可能的函数都有⾃⼰的参数集该怎么办?
The solution is dictionary unpacking. First, what does dictionary unpacking actually do? In the code below, line 6 and line 14 are doing the same thing, the only difference is that line 14 is using dictionary unpacking.
解决⽅案是打开字典。 ⾸先,字典解压缩实际上是做什么的? 在下⾯的代码中,第6⾏和第14⾏执⾏相同的操作,唯⼀的区别是第14⾏使⽤字典解压缩。
def user_print(user_name, user_type="regular", user_logged_in=False):
return f"{user_name} is a(n) {user_type} user and they are {'not ' if not user_logged_in else ''}logged in."
# 1. Without dictionary unpacking:
user_print(user_name="testuser1", user_type="admin", user_logged_in=True)
# 2. With dictionary unpacking:
args = {
"user_name": "testuser1",
"user_type": "admin",
"user_logged_in": True
}
user_print(**args)
Now, we only need to mildly adjust our earlier example to allow for any custom arguments in our dynamic functions:
现在,我们只需要稍微调整⼀下前⾯的⽰例,就可以在动态函数中包含任何⾃定义参数:
def add(x, to=1):
return x + to
def divide(x, by=2):
新疆伊犁旅游景点return x/by
def square(x):
return x**2
def invalid_op(x):
raise Exception("Invalid operation")
def perform_operation(x, chosen_operation, operation_args={}):
ops = {
"add": add,
"divide": divide,
"square": square
}
chosen_operation_function = (chosen_operation, invalid_op)
return chosen_operation_function(x, **operation_args)
国内游
def example_usage():
x = 1
x = perform_operation(x, "add", {"to": 4}) # Adds 4
x = perform_operation(x, "add") # Adds 1 since that's the default for 'add'
x = perform_operation(x, "divide", {"by": 2}) # Divides by 2
x = perform_operation(x, "square") # Squares the number
This approach can be useful in situations where you want your program to be highly configurable. For example, we can see that in the above code, the sequence of operations specified in the example_usage() function could instead have been defined in a configuration file such as JSON or YAML.

本文发布于:2023-05-26 12:33:06,感谢您对本站的认可!

本文链接:http://www.035400.com/whly/2/437061.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:代码   可能   参数   动态   定义   语句
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2024-2030 Comsenz Inc.Powered by © 文化旅游网 滇ICP备2022007236号-403 联系QQ:1103060800网站地图