Files
coding-mentor-agent/kb/python-course-kb-practical-python/wiki/exercises/7-8-simplifying-function-calls.md
T

1.4 KiB

id, source_exercise_id, title, section, source_path, source_repo, source_commit, student_visible_solution, has_private_solution, skip
id source_exercise_id title section source_path source_repo source_commit student_visible_solution has_private_solution skip
practical-python-7.8 7.8 Simplifying Function Calls 7.3 Returning Functions 07_Advanced_Topics/03_Returning_functions.md https://github.com/dabeaz-course/practical-python 93dca856b41c61a0a0f85ae334116e4c125629ea false false false

Exercise 7.8: Simplifying Function Calls

Source: Practical Python Programming, 07_Advanced_Topics/03_Returning_functions.md.

Exercise 7.8: Simplifying Function Calls

In the above example, users might find calls such as typedproperty('shares', int) a bit verbose to type--especially if they're repeated a lot. Add the following definitions to the typedproperty.py file:

String = lambda name: typedproperty(name, str)
Integer = lambda name: typedproperty(name, int)
Float = lambda name: typedproperty(name, float)

Now, rewrite the Stock class to use these functions instead:

class Stock:
    name = String('name')
    shares = Integer('shares')
    price = Float('price')

    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price

Ah, that's a bit better. The main takeaway here is that closures and lambda can often be used to simplify code and eliminate annoying repetition. This is often good.

关联来源