Terminology for class inheriting from dict

In this situation, would it be correct to say that f has and has a dict? "There" does not seem to be entirely correct. Does f

dictation have two different ways? What's the correct terminology to describe and think about this?

class Foo(dict):
    def __init__(self):
        self.name = "John"
        self["number"] = 42

f = Foo()

f.__dict__
>>> {'name': 'John'}          [A]
f.items()
>>> [('number', 42)]          [B]
f 
>>> {'number': 42}            [C]

      

Edit: I'm interested in a way to describe these dictionaries. What are the appropriate conditions to talk about it?

+3


source to share


3 answers


In terms of implementation, yes, f

both have a dict and are a dict. Are you adequately proved that both of __dict__

and f

exist as separate dictionaries.

However, I think a practical way to think about what f

has attributes is (via __dict__

), but it is also dict

(via subclass). You really shouldn't be referring directly to __dict__

; this is an implementation detail of the Python classes.



Of course Python is Python, there is no reason to hide the internal details from the programmer. "We all agree with adults," says Pythonism.

+2


source


It is more of an agnostic expression of the language, but there are two connections between certain classes:

  • has-a , which is used when describing the composition (for example, mixins or properties) and
  • is-a , which is used if the class is a subtype of another class.


Your class Foo

is dict

because it inherits from dict

. This is not what it has dict

, as there is no separate property that is a dictionary and it will also behave like a dict

if used as one (a-la duck typing ).

+1


source


Look at this:

class Foo(dict):
    def __init__(self):
        self.name = "John"
        self.number = 42
        self.num = 4


>>> f = Foo()
>>> f.__dict__
{'name': 'John', 'number': 42, 'num': 4}
>>> 

      

obj.__dict__

contains all variables.

>>> class cl:
    def __init__(self):
        self.val = 12


>>> f = cl()
>>> f.__dict__
{'val': 12}

      

0


source







All Articles