• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python的attrs表示什么

python 搞java代码 3年前 (2022-05-21) 32次浏览 已收录 0个评论

attr可看作是一个类装饰器但又不仅仅是简单的装饰器,他使得我们编写类变得更加简单轻松。下面先通过一个简单的例子来见识下attr的强大吧。
现在我们需要编写一个类,有a,b,c两个属性,正常的写法:

class A(object):
    def __init__(<a href="https://www.gaodaima.com/tag/self" title="查看更多关于self的文章" target="_blank">self</a>, a, b, c):
        self.a = a        self.b = b        self.c = c

www#gaodaima.com来源gaodai#ma#com搞*!代#%^码网搞代码

看起来也没那么复杂嘛。好了,现在领导说类的打印输出不好看,又不能进行比较,行吧,有需求就加吧。

from functools import total_ordering@total_orderingclass A(object):
    def __init__(self, a, b, c):
        self.a = a        self.b = b    def __repr__(self):
        return "ArtisanalClass(a={}, b={})".format(self.a, self.b)

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return NotImplemented
        return (self.a, self.b) == (other.a, other.b)

    def __lt__(self, other):
        if not isinstance(other, self.__class__):
            return NotImplemented
        return (self.a, self.b) < (other.a, other.b)

虽然看起来有点复杂,但是借助total_ordering,也算是以尽量少的代码实现了所需功能了吧。
但是,有没有更简洁的方式呢?让我们来看看借助于attr的实现:

import attr

@attr.sclass A(object):
    a = attr.ib()
    b = attr.ib()

更多学习内容,请点击Python学习网。

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python的attrs表示什么
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址