Pseudo-dictations as properties

I have a Python class Cthat should have two pseudo dict aand b. The term pseudo-dicts means that dictionaries do not actually exist and that they are β€œrecounted” every time the key is accessed.

In pseudocode, it will look like this:

class C:
    def a.__getitem__(self, key):
        return 'a'
    def b.__getitem__(self, key):
        return 'b'

>>> c = C()
>>> c.a['foo']
'a'
>>> c.b['bar']
'b'

I could implement a class for aand b, but since both have just a few short methods, I wonder if there is a more elegant and compact way to do this.

+3
source share
2 answers

Why not just define your own class?

class PseudoDict(object):
    def __init__(self, c):
        self.c = c

    def __getitem__(self, key):
        return self.c.somethingmagical()

class C(object):
    def __init__(self):
        self.a = PseudoDict(self)
        self.b = PseudoDict(self)

c = C()
print c.a['foo']
print c.b['bar']

, -, __getitem__.

+1

?

from collections import defaultdict
class C:
    a = defaultdict(lambda:'a')
    b = defaultdict(lambda:'b')

c=C()
print c.a['foo']
print c.b['bar']

, ?

from collections import defaultdict

class C:
    def __init__(self):
        self.a = defaultdict(self.geta)
        self.b = defaultdict(self.getb)
    def geta(self):
        return 'a'
    def getb(self):
        return 'b'

c=C()
print c.a['foo']
print c.b['bar']
+1

Source: https://habr.com/ru/post/1761665/


All Articles