0

I am creating an object that has a dictionary attribute. I want to control the keys and values allowed for elements. I (think I) know how to control the key and values when being set, but not when being added. For instance:

class A(object):
    def __init__(self):
        self.__d = {}
    @property
    def d(self):
        return self.__d
    @d.setter
    def d(self, d):
        # putting a condition on the keys and values
        self.__d = {k:d[k] for k in d if k < 10 and d[k] >0}

a = A()
a.d = {1:2, 2:3, 11:5, 5:-4}
print(a.d) #{1: 2, 2: 3} YAY!!

a.d[25] = -100
print(a.d) #{1: 2, 2: 3, 25: -100} BOOOOOOO (I wanted to filter out 25:-100)

I understand I can create a new dict like object inheriting from dict, but I feel like it should be able to be done using the @property decorator....?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • You need to subclass `dict` and override `__setitem__`. – kindall Jul 06 '17 at 22:17
  • As stated in the answer in the duplicate; when accessing through `a.d[25]` first the getter is used to get the dict, then the normal `dict` set function is used. – JohanL Jul 06 '17 at 22:17

0 Answers0