FreezeJ' Blog

Python_attr模块

2019-09-06

Python attr 模块demo代码

import attr
from attr.validators import instance_of


def check_str_len(instance, attribute, value):
    if not 10 > len(value) > 1:
        print(value)
        raise ValueError("wrong str len!")


@attr.s(auto_attribs=True, slots=True)
class Book(object):
    name: str  # 设置了auto_attribs会自动生成参数
    page: int
    book_type: list
    author: str = attr.ib(validator=[instance_of(str), check_str_len])  # 检查合法性,可以是多个条件
    price: float = attr.ib(converter=float)  # 类型转换为float
    secret: str = attr.ib(repr=False)  # 排除不输出
    comment: str = attr.ib(default='123')


a = Book('python test', 100, ['计算机', '编程'], '匿名', 30, 'yqgadfgwsrtqaavssdfa', '一本好书')
print(a)  # 不输出repr=False的项
print(a.__slots__)  # 开启slots=True
print(attr.asdict(a))  # 转换属性为dict输出


'''
console输出内容:
Book(name='python test', page=100, book_type=['计算机', '编程'], author='匿名', price=30.0, comment='一本好书')
('name', 'page', 'book_type', 'author', 'price', 'secret', 'comment', '__weakref__')
{'name': 'python test', 'page': 100, 'book_type': ['计算机', '编程'], 'author': '匿名', 'price': 30.0, 'secret': 'yqgadfgwsrtqaavssdfa', 'comment': '一本好书'}
'''

参考文章:

https://www.jianshu.com/p/2140b519028d

https://www.attrs.org/en/stable/examples.html

https://glyph.twistedmatrix.com/2016/08/attrs.html

Tags: Python
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏