Python Forum
Using Dictionaries in inheritance
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Dictionaries in inheritance
#1
I was working on a project when this situation occurred. I've defined a base class that initialises a dict and then I've the derived class that adds something more to the dict.

Now when I run the program, I end up getting a keyerror.
Here's the code I've used.

class Base:
    context = {}
    def __init__(self):
        context = {
            'style': [
                'apple',
                'balls'
            ],
            'script': [
                'cat',
                'dog'
            ]
        }

class Derived(Base):
    def __init__(self):
        self.context['style'].append('Kite')

obj = Derived()
print(obj.context)
I guess I've something silly.
Reply
#2
Since your Derived class has an __init__ too, you have to call the parent __init__ explicitly.
class Base:
    context = {}

    def __init__(self):
        self.context = {
            'style': [
                'apple',
                'balls'
            ],
            'script': [
                'cat',
                'dog'
            ]
        }


class Derived(Base):

    def __init__(self):
        Base.__init__(self)
        self.context['style'].append('Kite')


obj = Derived()
print(obj.context)
Reply
#3
In addition to what @gontajones said - Your code will create 2 distinct context attributes

Output:
In [5]: class A: ...: context = {} ...: def __init__(self): ...: self.context = {1:1} ...: In [6]: a = A() In [7]: a.context Out[7]: {1: 1} In [8]: A.context Out[8]: {}
One is available through the object reference; another - through the class reference. This is not a healthy practice. You may create a class level attribute and reference it in objects - if you don't update it within objects, and if you do want to update it - only through classmethods functions. Just FYI
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020