我的 python 数据类需要一个唯一的(无符号整数)id。这是非常相似 to 这个帖子 https://stackoverflow.com/questions/58101476/how-to-create-a-unique-and-incremental-id-in-a-python-class, but without明确的演员。
import attr
from attrs import field
from itertools import count
@attr.s(auto_attribs=True)
class Person:
#: each Person has a unique id
_counter: count[int] = field(init=False, default=count())
_unique_id: int = field(init=False)
@_unique_id.default
def _initialize_unique_id(self) -> int:
return next(self._counter)
还有更多“pythonic”解决方案吗?
Use a default factory instead of just a default. https://docs.python.org/3/library/dataclasses.html#default-factory-functions This allows to define a call to get the next id on each instantiation.
A simple means to get a callable that counts up is to use count().__next__
, the equivalent of calling next(...)
on a count
instance.1
常见的“无显式构造函数”库attr
and dataclasses
两者都支持这一点:
from itertools import count
from dataclasses import dataclass, field
@dataclass
class C:
identifier: int = field(default_factory=count().__next__)
import attr
@attr.s
class C:
identifier: int = attr.field(factory=count().__next__)
要始终使用自动生成的值并防止将其作为参数传递,请使用init=False
.
@dataclass
class C:
identifier: int = field(default_factory=count().__next__, init=False)
1 If one wants to avoid explicitly addressing magic methods, one can use a closure over a count
. For example, factory=lambda counter=count(): next(counter)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)