当参数传递给它们时,装饰器如何工作

时间:2017-12-16 06:48:06

标签: python python-3.x python-decorators

我只是想熟悉Python中的装饰器,但作为语言的新手,我无法理解为什么我会在下面得到这个:

带参数的装饰器的代码:

 itemindex = es.indices.create(
        index='mo-items-index-1',
        body={
        "settings": {
            "number_of_shards": 1,
            "analysis": {
                "filter": {
                    "autocomplete_filter": {
                        "type":     "edge_ngram",
                        "min_gram": 1,
                        "max_gram": 20
                    },
                    "custom_shingle": {
                        "type": "shingle",
                        "min_shingle_size": 2,
                        "max_shingle_size": 3,
                        "output_unigrams": True

                    },
                    "my_char_filter": {
                        "type": "pattern_replace",
                        "pattern": " ",
                        "replacement": ""
                    }
                },
                "analyzer": {
                    "autocomplete": {
                        "type":      "custom",
                        "tokenizer": "standard",
                        "filter": [
                            "lowercase",
                            "custom_shingle",
                            "autocomplete_filter",
                            "my_char_filter"
                        ]
                    }
                }
            }
        },
        "mappings": {
        "my_type": {
            "properties": {
                "item_id": {
                    "type":     "string",
                    "analyzer": "autocomplete",
            "search_analyzer": "standard"

                },
            "item_name": {
                    "type":     "string",
                    "analyzer": "autocomplete",
            "search_analyzer": "standard"

                }
            }
        }
    }
       },
        # Will ignore 400 errors, remove to ensure you're prompted
       ignore=400
    )

输出:

 res2 = es.search(index="mo-items-index-1", size=200, body={"query": {"multi_match": {
        "fields": [
            "item_name", "item_id"], "query": userQuery, "fuzziness": "AUTO"}}, "highlight": {

        "fields": {
            "item_name": {},
            "item_id": {}

        }
    }, })

有人能解释我为什么会得到"内部装饰"两次?

1 个答案:

答案 0 :(得分:0)

装饰器运行两次,因为你正在装饰两个函数。装饰器在定义每个修饰函数时运行,因为Python解析并在内部对程序进行字节编译。

装饰者是否接受参数并不重要;这就是装饰器用于 - 在定义另一个函数时运行函数。