I have an class that defines an 'alarm' and then one the defines a 'httpalarm'. Now a httpalarm shares many of the same properties as that of alarm (in fact is has all the same ones, plus others).
What I think I should be able to do is define these properties once as part of the alarm object, and then when httpalarm is created as a child of alarm, it should get all properties already. But it doesn't. At least, it doesn't appear to;
class alarm(object):
def __init__(self, severity, name, eventId):
self.severity = severity
self.name = name
self.eventId eventId
class httpalarm(alarm):
def __init__(self, **kwargs):
self._dict__.update(kwargs)
Now when I create an alarm object I get what I expect:
a = alarm('Critical', 'Name', '0x800111')
vars(a)
->
{'severity': 'Critical', 'name': 'Name', 'eventId': '0x800111'}
This is as expected. However when I create a httpalarm:
b = httpalarm(test = 'Test')
vars(b)
->
{'test': 'Test'}
This is unexpected. I was anticipating that the httpalarm b, would also have a severity, name and eventId attribute already set.
So rather than instance properties, I set the alarm class to use class properties:
class alarm(object):
severity = 'Warning'
name = None
eventId = None
and then again with no changed to httpalarm I tested again;
c = httpalarm(test='Test')
vars(c)
->
{'test': 'Test'}
Again, vars isn't showing all the other properties. However, they are being set as;
print c.severity
'Warning'
printing an inherited property does seem to work. And also using dir(c) to show the object does indeed return all the properties
dir(c)
->
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'eventId', 'name', 'severity', 'test']
I'm not really sure whats going on here. I'd like to create an alarm class that I can inherit from to save me having to define out the same properties all the time. What I'm trying to get is:
d = httpalarm(severity = 'Critical', name = 'Name', eventId = '0x800111', test = 'test')
and have the httpalarm instance d include all the properties from alarm as well as the properties from its own httpalarm class.
Edit: Following the submission from Corley Brigman I've got this working working as expected using:
class httpalarm(alarm):
def __init__(self,
**kwargs):
super(httpalarm, self).__init__()
for k,v in self.__dict__.iteritems():
if type(v) == tuple:
setattr(self, k, v[0])
self.__dict__.update(kwargs)