30秒学会 Python 片段 · 2023年7月22日

30秒学会 Python 片段 – Check property

Creates a function that will invoke a predicate function for the specified property on a given dictionary.

  • Return a lambda function that takes a dictionary and applies the predicate function, fn to the specified property.

代码实现

def check_prop(fn, prop):
  return lambda obj: fn(obj[prop])

使用样例

check_age = check_prop(lambda x: x >= 18, 'age')
user = {'name': 'Mark', 'age': 18}
check_age(user) # True

翻译自:https://www.30secondsofcode.org/python/s/check-prop