在Python檔案的相關部分Enum中,提到混合型別可用于確保專案屬于該型別并充當該型別的物件,如示例中所示:
class IntEnum(int, Enum):
pass
但是,檔案沒有給出任何關于如何使用自定義類作為混合型別的示例,我在這方面失敗了。甚至可能嗎?如果是這樣,我該怎么做?
我正在嘗試撰寫的代碼是
@dataclass
class Field:
dtype: str
name: str
@dataclass
class FwfField(Field):
width: int
def __post_init__(self):
if self.width <= 0:
raise ValueError("Field width must be positive.")
class CnefeSchema(FwfField, Enum):
state_code = ("int", "Código da UF", 2)
...
CnefeSchema當我從另一個檔案匯入或運行它時,我得到
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 from src.conf.schemas import CnefeSchema
File src/conf/schemas.py:25, in <module>
21 pass
24 # TODO automatically read schema from Layout
---> 25 class CnefeSchema(EnumFwfField, Enum):
27 @classmethod
28 def parse(cls) -> tuple[list, dict, dict]:
29 """
30 Get field widths, dtypes, and columns from schema.
31
(...)
34 as `pandas.read_fwf`.
35 """
File /usr/lib/python3.10/enum.py:298, in EnumMeta.__new__(metacls, cls, bases, classdict, **kwds)
296 enum_member._name_ = member_name
297 enum_member.__objclass__ = enum_class
--> 298 enum_member.__init__(*args)
299 # If another member with the same value was already defined, the
300 # new member becomes an alias to the existing one.
301 for name, canonical_member in enum_class._member_map_.items():
File <string>:4, in __init__(self, dtype, name, width)
File /usr/lib/python3.10/types.py:187, in DynamicClassAttribute.__set__(self, instance, value)
185 def __set__(self, instance, value):
186 if self.fset is None:
--> 187 raise AttributeError("can't set attribute")
188 self.fset(instance, value)
AttributeError: can't set attribute
我已經嘗試過:
- 定義另一個類,
EnumFwfField并將其用作混合,即
但我得到與上述相同的錯誤;class EnumFwfField(FwfField, Enum): pass class CnefeSchema(EnumFwfField, Enum): ... - 將
Enum欄位(在本例中為state_code)設定為FwfField,即
但后來我得到class CnefeSchema(FwfField, Enum): state_code = FwfField("int", "Código da UF", 2) ...Traceback (most recent call last): File "src/conf/schemas.py", line 25, in <module> class CnefeSchema(EnumFwfField, Enum): File "/usr/lib/python3.10/enum.py", line 298, in __new__ enum_member.__init__(*args) TypeError: FwfField.__init__() missing 2 required positional arguments: 'name' and 'width'
uj5u.com熱心網友回復:
您遇到的問題是因為在上面的代碼中,您的資料類中有一個name屬性Field,但Enum不允許您設定name屬性。
將該欄位重命名為其他名稱,例如'dname',它應該可以作業。
(3.11 中的錯誤資訊提供了更多資訊。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/494856.html
上一篇:如何覆寫派生FB中的結構
