I will summarize what I learned about python.
def test(a,b,c):
return {"a" : a ,'b' : b, 'c' : c}
print(test(b=3,c=3,a=66))
In this case, `{'a': 66,'b': 3,'c': 3}`
is output.
It can be executed by specifying the name of the argument like this.
(It's hard to understand and Sman)
You can specify a default argument in case you forget to specify an argument
def test(a=0,b=1,c=2):
return {"a" : a ,'b' : b, 'c' : c}
print(test())
>>> {'a': 0, 'b': 1, 'c': 2}
If * is used as part of a formal argument, a variable number of positional arguments are grouped into a tuple and set as a formal argument.
def test(*args):
print(args)
test(1,4,22,'hell')
>>> (1, 4, 22, 'hell')
It is not necessary to call the formal argument args when using *, but it is common to use __args __
You can use ** to combine keyword arguments into a single dictionary.
ef test(**kwargs):
print(kwargs)
test(akb=48,nogizaka=46,kkk="hello")
>>>{'akb': 48, 'nogizaka': 46, 'kkk': 'hello'}
When using * args and ** kwargs that combine positional arguments, the two must be arranged in this order.
docstring You can add a document to the function definition by adding a character string at the beginning of the function body.
def test(s):
'Returns the argument as is'
return s
print(test.__doc__)
>>>Returns the argument as is
I still don't understand the meaning of underscore.
I'm not sure what closures are, but I'll summarize them a bit.
def circle_area_func(pi):
"""Returns a function that finds the area of a circle"""
def circle_area(radius):
return pi * radius ** 2 #This pi is circle_area_func()The value specified in the argument of
return circle_area #Returns the function as a return value
#Pi 3.Generate a function to calculate the area when set to 14
ca1 = circle_area_func(3.14)
#Next, set the pi to 3.Generate a function when set to 141592
ca2 = circle_area_func(3.141592)
#The two functions created above have a radius=Get the operation result by giving 1 as an argument
ca1(1) #>>>3,14
ca2(1) #>>>3.141592
By using the closure feature in this way, you can dynamically create a "function that has the same logic but different parameters used inside" just by creating one function that creates and returns a function. .. With this mechanism, the feature (functional linguistic feature) that "not only variables but also processes (= functions) are made into parts and reused" is added to the language.
That's right ... I feel like I got the image. I'm not saying it can be used
In Python, you can use "lambda expressions" to create anonymous functions.
myfunc = lambda x: x ** 2
myfunc(5) # 25
myfunc(6) # 36
This is done using "def"
def myfunc(x):
return x ** 2
The process is the same as when defined as. In other words, in the form "lambda x: y", x is the argument and y is the return value.
Recommended Posts