3

I suppose i'm misunderstand how type inheritance work in python.

While i'm defining variable inside Parent class, any Child class inherited in parent referencing same variable from parent.

class Parent(object):
    store = dict()

class ChildA(Parent):
   pass

class ChildB(Parent):
   pass

ChildA.store['key1'] = 'val' 
ChildB.store['key2'] = 'val'

print ChildB.store['key1'] == ChildA.store['key2']

What i'm trying to achieve is store dictionary instance to be created in every Child class inherited from Parent. So referencing ChildB.store['key1'] would raise KeyError

I have tried to use __new__ to create dictionary instance while type is creating:

class NewParent(object):  
    def __new__(cls, *args, **kwargs):
        rv = super(NewParent,cls).__new__(cls, *args, **kwargs)
        rv.store = dict()
        return rv

But it's seems like __new__ running only before instantiating Child class, so referencing variable via type (e.g. Child.store is raising AttributeError)

So is there any way to achieve behavior i want?

2

1 Answer 1

3

You want to use a metaclass, which lets you initialize a class definition sort of like how a constructor lets you initalize an instance. For more details, see http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/.

Example:

#!/usr/bin/env python2

class ParentMeta(type):
    def __new__(meta, name, bases, dct):
        dct['store'] = dict()
        return super(ParentMeta, meta).__new__(meta, name, bases, dct)

class Parent(object):
    __metaclass__ = ParentMeta

class ChildA(Parent):
    pass

class ChildB(Parent):
   pass

ChildA.store['key1'] = 'val'
ChildB.store['key2'] = 'val'

print ChildB.store['key1'] == ChildA.store['key2']

will result in

Traceback (most recent call last):
  File "test.py", line 20, in <module>
    print ChildB.store['key1'] == ChildA.store['key2']
KeyError: 'key1'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.