简体   繁体   English

如何从声明的描述符生成类的 __init__ 方法?

[英]How to generate class's __init__ method from declared descriptors?

The example from python's documentation : python文档中的示例

class Component:

    name = String(minsize=3, maxsize=10, predicate=str.isupper)
    kind = OneOf('wood', 'metal', 'plastic')
    quantity = Number(minvalue=0)

    def __init__(self, name, kind, quantity):
        self.name = name
        self.kind = kind
        self.quantity = quantity

How can I make python to generate __init__ method for me?如何让 python 为我生成__init__方法?

You can use python's dataclasses and it will work just fine:您可以使用 python 的数据类,它会工作得很好:

from dataclasses import dataclass

@dataclass
class Component:

    name: str = String(minsize=3, maxsize=10, predicate=str.isupper)
    kind: str = OneOf('wood', 'metal', 'plastic')
    quantity: int = Number(minvalue=0)

Example:例子:

try:
    Component(name="Log", kind="wood", quantity=3)
except ValueError as e:
    print(e)
    
Expected <method 'isupper' of 'str' objects> to be true for 'Log'
c = Component(name="LOG", kind="wood", quantity=3)
[c.name, c.kind, c.quantity]
['LOG', 'wood', 3]

I found it very useful when dealing with classes which act as data containters with MANY descriptor-fields.我发现它在处理充当具有许多描述符字段的数据容器的类时非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM