from attr import attrs,attrib
@attrs
class Person:
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
@attrs
class Person:
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, attrib
def is_valid_gender(instance, attribute, value):
if value not in ('M', 'F'):
raise ValueError(f'gender {value} is not valid')
@attrs
class Person:
name = attrib(type = str)
age = attrib(type = str)
sex = attrib(validator=is_valid_gender)
from attr import attrs, attrib,validators
def is_valid_gender(instance, attribute, value):
if value not in ('M', 'F'):
raise ValueError(f'gender {value} is not valid')
def is_less_than_100(instance, attribute, value):
if value > 100:
raise ValueError(f'age {value} must less than 100')
@attrs
class Person:
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,validators
def to_int(value):
try:
return int(value)
except:
return None
@attrs
class Person:
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')