- Python Shortcuts, Commands, and Packages
- 4.2 Twenty-Two Programming Shortcuts
- 4.3 Running Python from the Command Line
- 4.4 Writing and Using Doc Strings
- 4.5 Importing Packages
- 4.6 A Guided Tour of Python Packages
- 4.7函数作为一类对象
- 4.8 Variable-Length Argument Lists
- 4.9修饰符and Function Profilers
- 4.10 Generators
- 4.11 Accessing Command-Line Arguments
- Chapter 4 Summary
- Chapter 4 Questions for Review
- Chapter 4 Suggested Problems
4.7函数作为一类对象
Another productivity tool—which may be useful in debugging, profiling, and related tasks—is to treat Python functions asfirst-classobjects. That means taking advantage of how you can get information about a function at run time. For example, suppose you’ve defined a function calledavg.
def avg(a_list): '''This function finds the average val in a list.''' x = (sum(a_list) / len(a_list)) print('The average is:', x) return x
The nameavgis a symbolic name that refers to a function, which in Python lingo is also a callable. There are a number of things you can do withavg,如验证其类型function. Here’s an example:
>>>type(avg)
We already know thatavgnames a function, so this is not new information. But one of the interesting things you can do with an object is assign it to a new name. You can also assign a different function altogether to the symbolic name,avg.
def new_func(a_list): return (sum(a_list) / len(a_list)) old_avg = avg avg = new_func
The symbolic nameold_avgnow refers to the older, and longer, function we defined before. The symbolic nameavgnow refers to the newer function just defined.
The nameold_avgnow refers to our first averaging function, and we can call it, just as we used to callavg.
>>>old_avg([4, 6])The average is 5.0 5.0
The next function shown (which we might loosely term a “metafunction,” although it’s really quite ordinary) prints information about another function—specifically, the function argument passed to it.
def func_info(func): print('Function name:', func._ _name_ _) print('Function documentation:') help(func)
If we run this function onold_avg, which has been assigned to our first averaging function at the beginning of this section, we get this result:
Function name: avg Function documentation: Help on function avg in module _ _main_ _: avg(a_list) This function finds the average val in a list.
We’re currently using the symbolic nameold_avgto refer to the first function that was defined in this section. Notice that when we get the function’s name, the information printed uses the name thatthe function was originally defined with.
All of these operations will become important when we get to the topic of “decorating” in Section 4.9, “Decorators and Function Profilers.”