0

Example 1: Inheriting a built-in data type (dictionary)

Class example_class(dict): 
    def __init__(self):
        dict.__init__(self)
        self["key1"] = "value1"
        self["key2"] = "value2"
        self.random_variable = 15

Example 2: No dictionary inheritance (but gets the same "result")

Class example2_class: 
    def __init__(self):
        self.example_dictionary = dict()  # or alternatively {}
        self.example_dictionary["key1"] = "value1"
        self.example_dictionary["key2"] = "value2"
        self.random_variable = 29    

Can someone explain the difference between Example 1 & 2, like advantages/disadvantages?

By inheriting from the build-in type dictionary you can overwrite (some) build-in methods, however I've seen code which inherits from these build-in data types without redefining any existing method, in this case I don't see why you would try to inherit a build-in data type instead of just creating an object in your init() method.

  • Yes, you can only find the right answers when you know the term "composition". I also pointed you to that with the duplicate. Neither of your "more useful" answers help you with the terminology that you really need to research this. I can undo the dupe closure if you want, but your question is too broad as it is. And the underlying question of "should I use composition or inheritance?" is largely opinionated without a _very specific_ use case. – Andras Deak -- Слава Україні Dec 22 '21 at 17:27
  • @AndrasDeak: Is there a thing such as opening a question for 24h and then closing again? Just wondering if somebody else had any new insights, but at heart the question is indeed similar to the proposed question. Anyway, love from Europe <3 – LegallyOverworked Dec 22 '21 at 17:51
  • @AndrasDeak Any idea on a better title? You can leave it closed and yes it is mostly an opinionated question. The linked question just has 3 major caviats in my opinion: 1) lacking example, which leads to some general answers (example are always clarifying), with example it's especially beginner friendly (it somewhat is a beginner question). 2) Nobody bothers to answer after 2010, which is a shame, some new functionalities/changes might favor one above the other (=> outdated information). 3) I'm specifically interested in *build-in data types* (such as lists, dictionaries, ....) – LegallyOverworked Dec 22 '21 at 18:24

2 Answers2

0

The vague answer is that inheriting a built-in type is useful if you want to define a class that has a bunch of the behaviors of that type. Your example2 won't behave like a dict unless you implement a bunch of magic methods that defer to self.example_dictionary; your example1 automatically does everything that a dict can do because it is a dict.

collections has some good concrete examples of types that inherit dict: defaultdict and Counter. If you were to implement those classes both with and without subclassing, you'd find that the subclassed implementation is significantly more straightforward -- in addition, subclassing means that if you use static type checking, a defaultdict (being a type of dict) is automatically accepted anywhere that a dict is, which is a desirable quality (since it is in fact a dict and does everything a dict can do).

Samwise
  • 68,105
  • 3
  • 30
  • 44
0

Generally second approach doesn't let you use all dict magic.

e_dict = example_class()

# all of this works
print(e1["key1"])
print(len(e1))
e1.update({"a": "b"})
print(e1) # it has nice representation
print("key1" in e1)

And much more

Of course you could implement all needed method but if you need some of dict magic, it's just easier to inherit from dict

There are more option, like MutableMapping or UserDict, you can read more information about it here

kosciej16
  • 6,294
  • 1
  • 18
  • 29