What's the preferred way to handle bad parameters when creating a new instance of a class?
For example, in a card game I might have a card class that can take Club, Heart, Diamond or Spade as the suit when creating a new instance (as well as the value). Do how do I handle someone passing it 'Kitten' as the suit?
I'm new to Python, but know a bit of Objective-C and Swift, and I think in those languages you could make the suit an enum and the compiler might pick up the incorrect value or you could return nil (Ocj-C) or an optional (swift) from the init of the card class.
I understand you cannot return 'nil' in Python (ie not create the instance) so perhaps I should return 'None' for the suit (or whatever member is affected) or even throw an exception? Or should I validate the inputs first?
The class __init__
method should raise a ValueError
if it is given something that is incorrect. When in doubt, check out the Zen of Python -- Errors should never pass silently .
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.