简体   繁体   English

在 python 数据类中创建唯一 ID

[英]Creating a unique id in a python dataclass

I need a unique (unsigned int) id for my python data class. This is very similar to this so post , but without explicit ctors.我的 python 数据 class 需要一个唯一的(无符号整数)ID。这与这篇帖子非常相似,但没有明确的 ctors。

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)

Is there any more-"pythonic" solution?还有更多的“pythonic”解决方案吗?

Use a default factory instead of just a default . 使用默认工厂而不是默认工厂。 This allows to define a call to get the next id on each instantiation.这允许定义一个调用以在每个实例化时获取下一个 id。
A simple means to get a callable that counts up is to use count().__next__ , the equivalent of calling next(...) on a count instance.获得计数的可调用对象的一种简单方法是使用count().__next__ ,相当于在count实例上调用next(...) 1 1个

The common "no explicit ctor" libraries attr and dataclasses both support this:常见的“无显式构造函数”库attrdataclasses都支持这一点:

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__)

To always use the automatically generated value and prevent passing one in as a parameter, use init=False .要始终使用自动生成的值并防止将一个值作为参数传入,请使用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 . 1如果想避免显式寻址魔术方法,可以对count使用闭包。 For example, factory=lambda counter=count(): next(counter) .例如, factory=lambda counter=count(): next(counter)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM