I'm working on a pyramid tutorial, but there are a lot of things I don't know.
For the time being, the sauce with @ came out. When using Java, I think it's an annotation, but That's not the case, and when I looked it up, it was a decorator.
Decorators are what you use to wrap an object. [Design pattern](http://en.wikipedia.org/wiki/%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3%83%91%E3% 82% BF% E3% 83% BC% E3% 83% B3_% 28% E3% 82% BD% E3% 83% 95% E3% 83% 88% E3% 82% A6% E3% 82% A7% E3% It was 82% A2% 29), that's right.
So, it seems that Python provides that decorator as a feature. I wrote a simple source using a decorator.
#Decorator (before the function to decorate"before",behind"after"To output)
def deco_test(func):
def wrapper(arg):
print("before")
func(arg)
print("after")
return wrapper
#Functions using decorators@Call the decorator using.
@deco_test
def hello(arg):
print("Hello, " + arg)
hello("world!")
The execution result is as follows. before Hello, world! after
By the way, the hello function using the decorator can be replaced with the function below.
def hello(arg):
print("Hello, " + arg)
hello = deco_test(hello)
I wasn't sure at first, but after trying various things, Python strongly learned that functions are also objects. The function is an argument. So, if you add () to the variable that stores the function and execute it.
It seems that you can write a program very flexibly, It's dynamically typed, and if you don't name it properly, It seems that a code that is very difficult to understand will be created.
By the way, the code that came out in the pyramid tutorial is as follows
@view_config(route_name='home', renderer='templates/mytemplate.pt')
def my_view(request):
try:
one = DBSession.query(MyModel).filter(MyModel.name == 'one').first()
except DBAPIError:
return Response(conn_err_msg, content_type='text/plain', status_int=500)
return {'one': one, 'project': 'tutorial'}
I was a little worried because this view_config was the class name, The @ part is the instance creation, and the argument is passed to init. The decorating function my_view is wrapped in the instance call call.
I think that's what it means, but verification is coming again.
Recommended Posts