In A开发者_如何学编程da, you can define a custom data type such as this
type Day_Of_Month is range 1 .. 31;
So now you can create a Day_Of_Month
variable that can only hold an int between 1 and 31. This is nice because we don't have to keep doing conditional checks when want to update the value, with proper exception handling.
Is there an easy way to do a similar thing in Python?
If this datatype is going to get used often, it might be worth creating a class for it and overwriting operators so it works more seamlessly. That way, all the exception handling is still internal to the datatype, and it gives you plenty of flexibility to define things like, for your example, differences in the number of days in February and March, or moving from month to month.
It is more a comment than an answer:
You could use datetime
module to work with date and time in Python. It will raise proper exceptions when necessary.
In general if you have data and some invariant that you'd like to keep during certain operations with that data then it is appropriate to create a class that allows you to perform those operations on the data while keeping the invariant.
Note: you don't want to implement a generic arithmetic class that just limits input/output for operations: it is not easy (see decimal.Decimal
, fractions.Fraction
) and it is not useful in this case e.g., what is the correct result of:
day_of_month + 1
To answer it you should know month, year (and timezone sometimes). Thus you begin to implement datetime
module and pytz
, dateutil
packages.
精彩评论