medium +20 pts

Descriptor Property

Implement a custom descriptor that validates integer assignments.

Implement a descriptor class `PositiveInt` that, when used as a class attribute, validates that the assigned value is an integer greater than zero. The descriptor should raise `TypeError` if the assigned value is not an integer, and `ValueError` if it is an integer but less than or equal to zero. Accessing the attribute should return the stored value. Deleting the attribute should delete the stored value using `del`. Define the class `PositiveInt` exactly as follows: ```python class PositiveInt: def __init__(self): # store per-instance data here pass def __get__(self, obj, objtype=None): # implement pass def __set__(self, obj, value): # implement pass def __delete__(self, obj): # implement pass ``` Your implementation must support the following usage: ```python class Person: age = PositiveInt() def __init__(self, age): self.age = age ``` - Assigning `age = 25` works. - Assigning `age = 3.14` raises `TypeError`. - Assigning `age = 0` raises `ValueError`. - Accessing `person.age` returns the stored integer. - Deleting `del person.age` makes subsequent access raise `AttributeError`. Write the `PositiveInt` class only. Do not modify the `Person` example.

Constraints

The descriptor must be per-instance (no data sharing between instances). The value stored must be exactly the integer provided. The descriptor must handle `__get__` with `obj=None` gracefully (should return the descriptor itself). Complexity: constant time operations.

Example

>>> class Person:
...     age = PositiveInt()
...     def __init__(self, age):
...         self.age = age
>>> p = Person(25)
>>> p.age
25
>>> p.age = 0
Traceback (most recent call last):
ValueError: age must be greater than zero
>>> p.age = 3.14
Traceback (most recent call last):
TypeError: age must be an integer
>>> del p.age
>>> p.age
Traceback (most recent call last):
AttributeError: 'Person' object has no attribute 'age'
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Store values in a dictionary on the descriptor instance, keyed by the owner object (using `id(obj)` or the object itself).
In `__set__`, first check `type(value) is int` (not `isinstance` to reject booleans) and raise `TypeError` otherwise.
If the value is an integer but `value <= 0`, raise `ValueError`.
In `__get__`, if `obj is None` return the descriptor itself, otherwise retrieve from the dictionary or raise `AttributeError`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.