首页 > 试题广场 >

以下代码使用了dataclasses的__post_init

[单选题]
以下代码使用了dataclasses的__post_init__和InitVar,输出是什么?
from dataclasses import dataclass, field, InitVar

@dataclass
class User:
    name: str
    password: InitVar[str]
    hashed: str = field(init=False)

    def __post_init__(self, password: str):
        self.hashed = f"hash({password})"

u = User("alice", "secret123")
print(f"{u.name} {u.hashed}, {hasattr(u, 'password')}")
  • alice hash(secret123), False
  • alice hash(secret123), True
  • alice secret123, False
  • alice secret123, True
  • 抛出TypeError
这个应该选B,A是题目一部分
发表于 2026-04-12 17:54:12 回复(0)