天天看點

Python程式設計:python-attrs子產品的簡單使用安裝代碼示例

文檔: http://www.attrs.org/en/stable/index.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}