You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am trying to create subclasses of a parent class which have their own default values but use the validator defined in the parent class. Is this possible? Here is a simple working example:
fromattrsimportdefine, field, validators@define(kw_only=True)classVehicle:
num_wheels: int=field(validator=validators.instance_of(int))
@num_wheels.validatordefvalidate_num_wheels(self, attribute, value) ->None:
ifvalue<=0:
raiseValueError("Must be greater than 0")
And here are some subclasses which I know don't work - but hopefully illustrate what I want to do.
@defineclassCar(Vehicle):
num_wheels: int=field(default=4) #! This doesn't work@defineclassMotorbike(Vehicle):
@num_wheels.default#! This doesn't work eitherdefdefault_num_wheels(self) ->int:
return2
I basically want to protect against a user doing Car(num_wheels=3.14) or Car(num_wheels=-1) accidently. And also have this work for Motorbike etc. But I want Car() and Motorbike() to return default values defined in the subclass. Is this possible?
The text was updated successfully, but these errors were encountered:
my1e5
changed the title
Define defaults for subclass that use validator of parent class?
Define defaults for subclass that uses validator of parent class?
Mar 13, 2024
I am trying to create subclasses of a parent class which have their own default values but use the validator defined in the parent class. Is this possible? Here is a simple working example:
And here are some subclasses which I know don't work - but hopefully illustrate what I want to do.
I basically want to protect against a user doing
Car(num_wheels=3.14)
orCar(num_wheels=-1)
accidently. And also have this work forMotorbike
etc. But I wantCar()
andMotorbike()
to return default values defined in the subclass. Is this possible?The text was updated successfully, but these errors were encountered: