示例工程 08-classes-mro-attributes

08-classes-mro-attributes/04-classmethod-staticmethod/classmethod_staticmethod.py

python · 0.8 KB

"""演示 classmethod 工厂与 staticmethod 工具函数。"""
 
from __future__ import annotations
 
 
class User:
    def __init__(self, name: str, role: str = "member") -> None:
        self.name = name
        self.role = role
 
    @classmethod
    def from_dict(cls, data: dict[str, str]) -> User:
        return cls(data["name"], data.get("role", "member"))
 
    @staticmethod
    def is_valid_name(name: str) -> bool:
        return bool(name) and name.isidentifier()
 
    def describe(self) -> str:
        return f"{self.name}:{self.role}"
 
 
def main() -> None:
    user = User.from_dict({"name": "Ada", "role": "admin"})
    print(f"user: {user.describe()}")
    print(f"valid: {User.is_valid_name('Ada')}, {User.is_valid_name('a-b')}")
 
 
if __name__ == "__main__":
    main()