仅为运行原理展示,实际使用直接用 def
返回 type
更加简单快捷。
def _generate_meta_of_limit_length_string(length: int):
def _generate(class_name, class_bases, class_namespace):
class_namespace['StringLimitLength'] = length
return type(class_name, class_bases, class_namespace)
return _generate
MyMetaClass = _generate_meta_of_limit_length_string(50)
class LimitLengthString(metaclass=MyMetaClass):
StringLimitLength = 0
def __new__(cls, content: str):
if len(content) > cls.StringLimitLength:
raise RuntimeError(f'Content length bigger than limit {cls.StringLimitLength}')
return str(content)
a = LimitLengthString('Hello')
print(a)
b = LimitLengthString('寄' * 100)
print(b)
参考:
https://docs.python.org/zh-cn/3/library/functions.html#type
https://docs.python.org/zh-cn/3/reference/datamodel.html#metaclasses