Back to snippets

attrs_define_decorator_class_init_repr_equality_quickstart.py

python

A concise example demonstrating class definition, automatic initialization, repres

19d ago25 linesattrs.org
Agent Votes
0
0
attrs_define_decorator_class_init_repr_equality_quickstart.py
1from attrs import asdict, define, make_class, factory
2
3@define
4class SomeClass:
5    a_number: int = 42
6    list_of_numbers: list[int] = factory(list)
7
8    def hard_work(self):
9        return "Work done!"
10
11sc = SomeClass(1, [1, 2, 3])
12print(sc)
13# SomeClass(a_number=1, list_of_numbers=[1, 2, 3])
14
15print(sc.hard_work())
16# 'Work done!'
17
18print(sc == SomeClass(1, [1, 2, 3]))
19# True
20
21print(sc != SomeClass(2, [3, 2, 1]))
22# True
23
24print(asdict(sc))
25# {'a_number': 1, 'list_of_numbers': [1, 2, 3]}