I wish the East Wind, and a total calm
Yan Yang zi mo luo cheng Dong
Always at the same time, swimming all over the aromatic plexus
The bitter rush of gathering and parting, this hate infinite
This year the flower wins last year red
But next year the flower is better, knows with WHO.
Xiao Ling Ouyang Xiu, a double tune of wave scouring sand
Some people say that everything in Python is an object, so let's find out today how the functions in Python are being instantiated.
The references in this article are: The function object of the Python advanced tutorial Dive into Python3 Liaoche's official website
This article directory
The Magic object function function in Python can also do objects automatically build a set of functions from the file read function configuration with generator to generate functions to sort out the idea built-in higher-order function map reduce filter sorted What other anonymous functions do you want to breathe in the last words of the decorator?
the Magic object in Python--function
In English, according to the suffix, the plural form of the noun will also be different.
Let's take a look at three pieces of code first.
The first paragraph is a more conventional way of thinking, passing in the noun, and then making a judgment and getting the plural form.
def plural (noun):
if Re.search (' [sxz]$ ', noun): return
re.sub (' $ ', ' es ', noun) elif re.search
(' [^ aeioudgkprt]h$ ', noun): return
re.sub (' $ ', ' es ', noun)
elif re.search (' [^aeiou]y$ ', noun]: return
re.sub ( ' y$ ', ' ies ', noun)
else: return
noun + ' s '
The above code uses the RE module, if you are not familiar with the module, you can see here.
Of course you don't understand or you can, and our focus is on understanding the features of functions in Python, right?
It's very prosaic, isn't it.
Take a look at the following abstract: functions can also be objects ~
Import re
def match_sxz (noun): return
re.search (' [sxz]$ ', noun]
def apply_sxz (noun): return
re.sub (' $ ', ' es ', noun
def match_h (noun): return
re.search (' [^aeioudgkprt]h$ ', noun)
def apply_h (noun):
Return re.sub (' $ ', ' es ', noun)
def match_y (noun): return
re.search (' [^aeiou]y$ ', noun)
def apply_y (noun) : Return
re.sub (' y$ ', ' ies ', noun)
def match_default (noun): return
True
def apply_default (noun): return
noun + ' s '
rules = ((Match_sxz, APPLY_SXZ),
(Match_h, Apply_h), (
match_y, apply_y)
, ( Match_default, Apply_default)
def plural (noun):
for Matches_rule, apply_rule in rules:
if Matches_rule (noun): return
apply_rule (noun)
#测试
a=[' Apple ', ' watch ', ' agency ' to
I in a:
Print (' {0}: {1} '. Format (i,plural (i)))
Here we introduce a concept of Python--the object of the function as well.
You can have a pair of functions in one tuple (rules).
But is it possible for us to continue simplifying here? For example, this function of automatically building rule tuple.
The answer is yes, each pair of functions in rule is the same return type. Then: automatically build a set of functions
Import re
def build_match_and_apply_functions (pattern, search, replace):
def matches_rule (word):
return Re.search (pattern, word)
def apply_rule (word): return
re.sub (search, replace, word) return
(matches_rule , Apply_rule)
Define two functions in a function, and then return.
So, we just need to define one of these data structures:
patterns = \
(
' [sxz]$ ', ' $ ', ' es '),
(' [^aeioudgkprt]h$ ', ' $ ', ' es ')
, ("(qu|[ ^aeiou] y$ ', ' y$ ', ' ies '),
(' $ ', ' $ ', ' s ')
rules = [Build_match_and_apply_functions ( Pattern, search, replace) for
(mode, search, replace) in patterns]
Read the function "Configuration" from the file
You ask me, could you please be a little simpler.
OK, like this:
Read this patterns from the file:
[sxz]$ $ es
[^aeioudgkprt]h$ $ es
[^aeiou]y$ y$ ies
$ $ s
Import re
def build_match_and_apply_functions (pattern, search, replace):
def matches_rule (word):
return Re.search (pattern, word)
def apply_rule (word): return
re.sub (search, replace, word) return
(matches_rule , apply_rule)
rules = [] with
open (' Plural4-rules.txt ', encoding= ' Utf-8 ') as Pattern_file:
Pattern_file: Pattern
, search, replace = Line.split (None, 3)
Rules.append (build_match_and_apply_functions (Pattern
, search, replace))
You ask: This can also write a little more refined.
This one... I can do that. We can function this part from file to rule: using generators to generate functions
def rules (Rules_filename):
with open (Rules_filename, encoding= ' Utf-8 ') as Pattern_file: For line in
Pattern_ File: Pattern
, search, replace = Line.split (None, 3)
#看这里.
yield build_match_and_apply_functions (pattern, search, replace)
def plural (noun, rules_filename= ' Plural5-rules.txt '):
for Matches_rule, apply_rule in Rules (Rules_filename):
if Matches_rule (noun):
return apply_rule (noun)
raise valueerror (' No matching rule for {0} '. Format (noun))
Yield means pausing the current function and returning the caller.
Here we need to introduce a new concept: generator.
This concept is more important, but we're not going to discuss it here. Organize your thoughts .
We have found that, in fact, we have said so much, is to prove a point: the function can also be used like an integer, String. This is an important goal, and we must be aware of it: from now on, a function is no longer the kind we understand in C, but an object that is an integer, a string.
Let's take a little break, and we're going to look at it. In Python, functions are meant to be objects: built-in higher-order functions
In Python, there are several more commonly used function-parameter functions (not a bit around the mouth ~), respectively, map, reduce, filter, and sort. After looking at their definition, you can actually write them out. Map
def func (x):
return x+3
result=map (func,[1,2,3,5,7))
Return result is:
[4,5,6,8,10]
You've actually guessed it, it's nothing more than a traversal on [1,2,3,5,7], passing each value to the first parameter: Func.
Let's try to complete a map of our own to try:
#朴素的my_map:)
def my_map (fun,lst):
res=[] for
i-LST:
res.append (Fun (i)) return
Res
Try this:
Result=my_map (func,[1,2,3,4,5])
>>> result
[4, 5, 6, 7, 8]
It worked. Reduce
As for reduce, um. The effect of this is this:
Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)
First compute temp=f (X1,X2), then compute temp=f (temp,3), then Temp=f (temp,x4) ...
This is also very simple to write:
def My_reduce (fun,lst):
temp=lst[0] for
i in range (1,len (LST)):
Temp=fun (temp,i) return
Temp
We've conquered two. and the filter and the sort!.
If you feel tired, it doesn't matter, the author wrote this blog for nearly a day ~ filter
I think you can even guess from the name of the number of what it does:
Yes, filtration.
def is_odd (n): Return
n% 2 = 1
list (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
We'll do it as usual, but I'll simplify it with a little trick:
def my_filter (fun,lst): Return
[I to I in LST if Fun (i)]
(In fact, the map above can also write OH) sorted
We can guess one or two by name.
Do:
Sorted ([5, -12, 9, -21])
[-21,-12, 5, 9, 36]
This is a sort of higher order function:
We can customize the sorted key
Sorted ([' Bob ', ' about ', ' Zoo ', ' credit '], key=str.lower)
[' About ', ' Bob ', ' Credit ', ' Zoo ']
Notice the Key=str.lower, so not in the order of the default ABCD...ABC. It is decided by its lower case.
Key is a function. We can also customize its return value. there's nothing else.
If you're not tired, it's okay to keep reading, even if you forget most of the previous stuff. Just keep that impression on you: A function is an object.
Next, we'll look at a couple of questions: function as return value anonymous function adorner function partial function
In fact, the 1th we have used before, we no longer in-depth. First look at the post three: anonymous function .
Let's take a look at a piece of code like this:
List (lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]) [1, 4, 9, 16, 25, 36, 49, 64, 81
]
The lambda x:x*x effect here is equivalent to defining a function
def fun (x): Return
x*x
But obviously it's a lot simpler and you don't have to name the function anymore.
This is called a lambda expression, and it is already supported in C + + 11.
There is no problem with the lambda as the return value:
def build (x, y): Return
lambda:x * x + y * y
Take a deep breath--the decorator .
The adorner is slightly more complex than the previous ones:
We now know that a function is an object, so we can assign a value to an object using a function, like an integer or a string:
def power (x): Return
x*x
#请使用函数名来赋值
f=power
#调用
F (5)
#输出25
Now look at this function:
def get_new_fun (fun):
def new_fun (x): Return
1+fun (x) return
New_fun
What happened. We passed in a function fun and built a new function. This is called the adorner pattern: building new functions on the basis of not changing the original function.
We can pass
F=get_new_fun (Power)
To get a new function.
There is also a way to define a function directly as a new function
@get_new_fun
def Fun (x): Return
x*x
Fun (5)
#结果是26
Last Words
In fact, the author of the contact function of the program is only one day, I write Python blog probably also persisted for nearly two weeks, I just in the best understanding of their own way to tidy up the current information I see. If there is any mistake, please correct me.