Hello! I’ve just finished the School Catalogue project (https://www.codecademy.com/courses/learn-intermediate-python-3/projects/python-school-catalogue) and I have a few questions. In the project instructions, inside the properties of the classes, it says that name has to be a string, level has to be either 'primary'
, 'middle'
or 'high'
, numberOfStudents has to be an integer and so on. The question is: how can I limit the type of input that can be inserted when instantiating a class?
Thank you in advance
Hey, welcome to the forums!
So you can’t unfortunately force a particular attribute to be of a certain type (see note), however what I’d suggest doing is checking what the type is or each of the relevant properties, when they are set/updated and return an error if not. See: Getters and Setters: Manage Attributes in Python – Real Python for a couple approaches - either manual setters or @property
decorators would work, but imho the decorator approach is a bit more “pythonic”.
nb: Python does have type hinting, which says what types variables etc should be, but it is not enforced by Python itself, it’s purely there as a guide and can be ignored: typing — Support for type hints — Python 3.11.4 documentation