Python编程:python-attrs模块的简单使用
  TEZNKK3IfmPf 2023年11月15日 24 0

文档:https://www.ctyun.cn/portal/link.html?target=http%3A%2F%2Fwww.attrs.org%2Fen%2Fstable%2Findex.html

attrs 可以简单理解为namedtuple的增强版

安装

pip install attrs

代码示例

1、定义一个tuple

p1 = (1, 2)
p2 = (1, 2)

print(p1 == p2)
# True
print(p1)
# (1, 2)

2、namedtuple定义一个类

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])

p1 = Point(1, 2)
p2 = Point(1, 2)

print(p1 == p2)
# True
print(p1)
# Point(x=1, y=2)

3、使用 attr动态定义一个类

import attr

Point = attr.make_class("Point", ["x", "y"])

p1 = Point(1, 2)
p2 = Point(1, 2)

print(p1 == p2)
# True
print(p1)
# Point(x=1, y=2)

4、使用 attr定义一个类

import attr

@attr.s
class Point(object):
    x = attr.ib(default=1)  # 定义默认参数
    y = attr.ib(kw_only=True)  # 关键字参数


p1 = Point(1, y=2)
p2 = Point(y=2)

print(p1 == p2)
# True
print(p1)
# Point(x=1, y=2)

print(attr.asdict(p1))  # 转为字典格式
# {'x': 1, 'y': 2}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年03月30日   26   0   0 htmlhtml5
  TEZNKK3IfmPf   2024年03月29日   30   0   0 htmlhtml5
  TEZNKK3IfmPf   2024年03月29日   50   0   0 htmlhtml5
  TEZNKK3IfmPf   2024年03月22日   55   0   0 htmljava
  TEZNKK3IfmPf   2024年03月29日   32   0   0 htmlhtml5
  TEZNKK3IfmPf   2024年03月29日   28   0   0 htmljQuery
  TEZNKK3IfmPf   2024年03月22日   42   0   0 htmlreact
TEZNKK3IfmPf