“@”——装饰器

为“增强”与重用,在不修改“函数”或“类”的前提下增加新的功能,装饰器也为一个“函数”或者“类”(所以有四种分类)。且与java不同python的函数可以作为普通变量传递给其他函数,即可得到以下的装饰器的例子。

# 本例子为使用装饰器计算代码的运行时间
import time
def display_time(func):# 装饰器函数的”注册“def wrapper(*args):t1 = time.time()result = func(*args)t2 = time.time()print('Total Time is {:.4}'.format(t2 - t1))return resultreturn wrapper# 使用
@display_time
def func():pass

例1.@Model.register(“name”)

在name.py中有

from allennlp.models.model import Model
@Model.register("name")
class NaMe(Model):

在这种情况下装饰器自身多为类,即类装饰器装饰类的情况。比如调用allennlp中的Model类中的register方法,传入参数为字符串。"name"和需要装饰的类。

# 使用的例子 https://snyk.io/advisor/python/allennlp/functions/allennlp.models.model.Model.register
from typing import Dict, Optional, List, Anyimport torch
import torch.nn.functional as F
from allennlp.data import Vocabulary
from allennlp.models.model import Model
from allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder
from allennlp.nn import InitializerApplicator, RegularizerApplicator
from allennlp.nn import util
from allennlp.training.metrics import CategoricalAccuracy, F1Measure
from overrides import overrides@Model.register("text_classifier")
class TextClassifier(Model):"""Implements a basic text classifier:1) Embed tokens using `text_field_embedder`2) Seq2SeqEncoder, e.g. BiLSTM3) Append the first and last encoder states4) Final feedforward layerOptimized with CrossEntropyLoss.  Evaluated with CategoricalAccuracy & F1."""def __init__(self, vocab: Vocabulary,text_field_embedder: TextFieldEmbedder,text_encoder: Seq2SeqEncoder,classifier_feedforward: FeedForward,verbose_metrics: False,initializer: InitializerApplicator = InitializerApplicator(),regularizer: Optional[RegularizerApplicator] = None,) -> None:super(TextClassifier, self).__init__(vocab, regularizer)self.text_field_embedder = text_field_embedderself.num_classes = self.vocab.get_vocab_size("labels")self.text_encoder = text_encoderself.classifier_feedforward = classifier_feedforwardself.prediction_layer = torch.nn.Linear(self.classifier_feedforward.get_output_dim()  , self.num_classes)self.label_accuracy = CategoricalAccuracy()self.label_f1_metrics = {}self.verbose_metrics = verbose_metricsfor i in range(self.num_classes):self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace="labels")] = F1Measure(positive_label=i)self.loss = torch.nn.CrossEntropyLoss()self.pool = lambda text, mask: util.get_final_encoder_states(text, mask, bidirectional=True)initializer(self)@overridesdef forward(self,text: Dict[str, torch.LongTensor],label: torch.IntTensor = None,metadata:  List[Dict[str, Any]] = None) -> Dict[str, torch.Tensor]:"""Parameters----------text : Dict[str, torch.LongTensor]From a ``TextField``label : torch.IntTensor, optional (default = None)From a ``LabelField``metadata : ``List[Dict[str, Any]]``, optional, (default = None)Metadata containing the original tokenization of the premise andhypothesis with 'premise_tokens' and 'hypothesis_tokens' keys respectively.Returns-------An output dictionary consisting of:label_logits : torch.FloatTensorA tensor of shape ``(batch_size, num_labels)`` representing unnormalised log probabilities of the label.label_probs : torch.FloatTensorA tensor of shape ``(batch_size, num_labels)`` representing probabilities of the label.loss : torch.FloatTensor, optionalA scalar loss to be optimised."""embedded_text = self.text_field_embedder(text)mask = util.get_text_field_mask(text)encoded_text = self.text_encoder(embedded_text, mask)pooled = self.pool(encoded_text, mask)ff_hidden = self.classifier_feedforward(pooled)logits = self.prediction_layer(ff_hidden)class_probs = F.softmax(logits, dim=1)output_dict = {"logits": logits}if label is not None:loss = self.loss(logits, label)output_dict["loss"] = loss# compute F1 per labelfor i in range(self.num_classes):metric = self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace="labels")]metric(class_probs, label)self.label_accuracy(logits, label)return output_dict@overridesdef decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:class_probabilities = F.softmax(output_dict['logits'], dim=-1)output_dict['class_probs'] = class_probabilitiesreturn output_dictdef get_metrics(self, reset: bool = False) -> Dict[str, float]:metric_dict = {}sum_f1 = 0.0for name, metric in self.label_f1_metrics.items():metric_val = metric.get_metric(reset)if self.verbose_metrics:metric_dict[name + '_P'] = metric_val[0]metric_dict[name + '_R'] = metric_val[1]metric_dict[name + '_F1'] = metric_val[2]sum_f1 += metric_val[2]names = list(self.label_f1_metrics.keys())total_len = len(names)average_f1 = sum_f1 / total_lenmetric_dict['average_F1'] = average_f1metric_dict['accuracy'] = self.label_accuracy.get_metric(reset)return metric_dict

例2. @property

使用@property装饰器来创建只读属性。

@property装饰器会将方法转换为相同名称的只读属性:

class DataSet(object):def __init__(self):self._onlyreadvalue = 1@propertydef method_with_property(self):  ##含有@property# 方法加入@property后,这个方法相当于一个属性# 这个属性可以让用户进行使用,而且用户有没办法随意修改。return 15def method_without_property(self):  ##不含@property  须正常调用,即在后面加()   print(l.method_without_property())return 15@propertydef expose_value(self):  # 方法加入@property后,这个方法相当于一个属性,这个属性可以让用户进行使用,而且用户有没办法随意修改。return self._onlyreadvaluel = DataSet()
print(l.method_with_property)  # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。

@Model.register(“name“) python装饰器相关推荐

  1. Python 装饰器记录总结 (终极版)

    Python 装饰器记录总结 (终极版) 原文链接:http://magicroc.com/2017/04/10/Python装饰器记录总结/ 装饰器是一个函数,一个用来包装函数的函数,装饰器在函数申 ...

  2. python装饰器类-Python类装饰器

    上次介绍了Python的函数装饰器,这次我们来讲一讲Python的类装饰器. Python的类装饰器基本语法如下: defdecorator(cls):print "6666666" ...

  3. Python 装饰器 函数

    Python装饰器学习(九步入门):http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 浅谈Python装饰器:https://b ...

  4. Python装饰器详解,详细介绍它的应用场景

    装饰器的应用场景 附加功能 数据的清理或添加: 函数参数类型验证 @require_ints 类似请求前拦截 数据格式转换 将函数返回字典改为 JSON/YAML 类似响应后篡改 为函数提供额外的数据 ...

  5. python装饰器理解_如何理解Python装饰器?

    首先,本垃圾文档工程师又来了.开始日常的水文写作.起因是看到这个问题如何理解Python装饰器?,正好不久前给人讲过这些,本垃圾于是又开始新的一轮辣鸡文章写作行为了. 预备知识 首先要理解装饰器,首先 ...

  6. 通过 Python 装饰器实现DRY(不重复代码)原

    通过 Python 装饰器实现DRY(不重复代码)原 Python装饰器是一个消除冗余的强大工具.随着将功能模块化为大小合适的方法,即使是最复杂的工作流,装饰器也能使它变成简洁的功能. 例如让我们看看 ...

  7. 通过 Python 装饰器实现DRY(不重复代码)原则

    通过 Python 装饰器实现DRY(不重复代码)原则 英文原文:DRY Principles through Python Decorators Python装饰器是一个消除冗余的强大工具.随着将功 ...

  8. 利用亚运会,读懂 Python装饰器

    阅读文本大概需要 5 分钟. 2018 年印度雅加达亚运会已接近尾声,中国在金牌榜和总奖牌榜都遥遥领先于第二名的日本,我也是一名体育爱好者,平时有比赛也会看.看到中国的国旗在海外飘扬,内心会格外的自豪 ...

  9. 10个美妙的Python装饰器

    10个美妙的Python装饰器 对Python编程语言中我最喜欢的一些装饰器的概述. 简介 关于Python编程语言的伟大之处在于,它在一个小包里装了所有的功能,这些功能非常有用.很多特性可以完全改变 ...

最新文章

  1. Cracking the coding interview--Q1.4
  2. 深度学习框架PyTorch一书的学习-第四章-神经网络工具箱nn
  3. 吴裕雄--天生自然 高等数学学习:微分中值定理与导数的应用
  4. 如何屏蔽LOGD\LOGI等打印输出
  5. redis 验证消息队列也是写磁盘的
  6. 数据可视化——ECharts基础
  7. 练习1,从文件到数据库
  8. stm32点亮流水灯(小白的求学之路)
  9. Scene Graph(视觉关系场景图检测)
  10. 一个基于高阶图匹配的多目标跟踪器:Online Multi-Target Tracking with Tensor-Based High-Order Graph Matching
  11. 【辗转反侧不得眠,心中疑惑何时解】---前段时间安装了showdoc,由于停电忘记怎么安装的了--稀里糊涂的重启showdoc
  12. 字节跳动 C++面经总结第四期
  13. kafka 0.10.0 producer java代码实现
  14. 4.2 Ansible中的常用模块
  15. BrupSuite Repeater模块
  16. 【GlobalMapper精品教程】021:利用控制点校正栅格图像
  17. airplay IOS 多部手机同时投屏
  18. 新建一个Menu菜单项
  19. 关于开展第六批山东省首版次高端软件申报工作的通知
  20. 揭示微软鲜为人知的秘密:观止--微软创建NT和未来的夺命狂奔 (Show Stopper!中文版)...

热门文章

  1. 【《WebGL编程指南》读书笔记——着色器和程序对象的准备】
  2. 树莓派4b入门以及各种系统烧录问题分享
  3. 【今日荐文】一本开源的程序员快速成长秘笈---康德胜
  4. 分享几个CDN加速服务
  5. 关于Multisim仿真电容充电曲线的设置方法
  6. Mathorcup数学建模竞赛第六届-【妈妈杯】A题:水产养殖池塘综合研究(附一等奖获奖论文、lingo和matlab代码)
  7. 宝塔绑定域名访问不了_建站系列教程(二)--本地局域网访问和域名解析
  8. 计算机提示pdf不能加载,Win7打开PDF文件提示无法自定义打开程序的解法
  9. 温度上报实时监控项目——客户端
  10. 重拾编程之路--jeetcode(java)--Range Sum Query - Immutable