简体   繁体   中英

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

The 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

How can I make python to generate __init__ method for me?

You can use python's dataclasses and it will work just fine:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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