如何从声明的描述符生成 class 的 __init__ 方法?
How to generate class's __init__ method from declared descriptors?
example from python's documentation:
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]
我发现它在处理 类 时非常有用,它充当具有许多描述符字段的数据容器。
example from python's documentation:
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]
我发现它在处理 类 时非常有用,它充当具有许多描述符字段的数据容器。