簡體   English   中英

如何從聲明的描述符生成類的 __init__ 方法?

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

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

如何讓 python 為我生成__init__方法?

您可以使用 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)

例子:

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]

我發現它在處理充當具有許多描述符字段的數據容器的類時非常有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM