from attr import attrs,attrib@attrsclassPerson: name =attrib(type =str,default="") age =attrib(type =int,default=0) sex =attrib(type =str,default="")if__name__=='__main__': first_person =Person("John",18,"M")print(first_person)Out:Person(name='John', age=18, sex='M')
from attr import attrs,attrib@attrsclassPerson: name =attrib(type =str) age =attrib(init=False) sex =attrib(type =str)first =Person("John","M")# Person(name='John', age=NOTHING, sex='M')second =Person("Mike",89,"M")#TypeError: __init__() takes 3 positional arguments but 4 were given
from attr import attrs,attrib@attrsclassPerson: name =attrib(type =str) age =attrib(type =str) sex =attrib(kw_only=True)first =Person("John",18,sex="M")#Person(name='John', age=18, sex='M')
from attr import attrs, attribdefis_valid_gender(instance,attribute,value):if value notin ('M','F'):raiseValueError(f'gender {value} is not valid')@attrsclassPerson: name =attrib(type =str) age =attrib(type =str) sex =attrib(validator=is_valid_gender)
from attr import attrs, attrib,validatorsdefis_valid_gender(instance,attribute,value):if value notin ('M','F'):raiseValueError(f'gender {value} is not valid')defis_less_than_100(instance,attribute,value):if value >100:raiseValueError(f'age {value} must less than 100')@attrsclassPerson: name =attrib(type =str) age =attrib(validator=[validators.instance_of(int), is_less_than_100]) sex =attrib(validator=[validators.instance_of(str),is_valid_gender])
Convertor
from attr import attrs, attrib,validatorsdefto_int(value):try:returnint(value)except:returnNone@attrsclassPerson: name =attrib(type =str) age =attrib(converter=to_int) sex =attrib(validator=validators.instance_of(str))last_person =Person("xiaobai","35","M")print(last_person)Out:Person(name='xiaobai', age=35, sex='M')