Issue
I have created a base class:
class Thing():
def __init__(self, name):
self.name = name
I want to extend the class and add to the init method so the that SubThing has both a name and a time property. How do I do it?
class SubThing(Thing):
# something here to extend the init and add a "time" property
def __repr__(self):
return '<%s %s>' % (self.name, self.time)
Any help would be awesome.
Solution
You can just define __init__ in the subclass and call super to call the parents' __init__ methods appropriately:
class SubThing(Thing):
def __init__(self, *args, **kwargs):
super(SubThing, self).__init__(*args, **kwargs)
self.time = datetime.now()
If you're still on Python 2.x, make sure the base class is a subclass of object, as super won't work with old-style classes:
class Thing(object):
...
Answered By - Jesse Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.