[英]How to generate __init__ for class with custom descriptors in Python?
[英]How to generate class's __init__ method from declared descriptors?
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.