【发布时间】:2019-02-07 05:15:30
【问题描述】:
考虑以下数据类。我想防止使用__init__ 方法直接创建对象。
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class C:
a: int
@classmethod
def create_from_f1(cls, a: int) -> C:
# do something
return cls(a)
@classmethod
def create_from_f2(cls, a: int, b: int) -> C:
# do something
return cls(a+b)
# more constructors follow
c0 = C.create_from_f1(1) # ok
c1 = C() # should raise an exception
c2 = C(1) # should raise an exception
例如,如果直接将对象创建为c = C(..),我想强制使用我定义的其他构造函数并引发异常或警告。
到目前为止我尝试过的如下。
@dataclass
class C:
a : int = field(init=False)
@classmethod
def create_from(cls, a: int) -> C:
# do something
c = cls()
c.a = a
return c
在field 中使用init=False,我阻止a 成为生成的__init__ 的参数,因此这部分解决了问题,因为c = C(1) 引发了异常。
另外,我不喜欢它作为解决方案。
有没有直接的方法来禁止从类外部调用 init 方法?
【问题讨论】:
标签: python class python-3.7 python-dataclasses