Passing arguments to subclasses

Gary Herron gherron at islandtraining.com
Mon Jun 23 17:59:31 CEST 2008


John Dann wrote:
> May I ask a simple newbie question, which I presume is true, but for
> which I can't readily find confirmation:
>
> Let's say I have a parent class with an __init__ method explicitly
> defined:
>
> class ParentClass(object):
> 	def __init__(self, keyword1, keyword2):
> 		etc
>
> and I subclass this:
>
> class ChildClass(ParentClass):
> 	# No __init__ method explicitly defined
>
> Now I presume that I can instantiate a child object as:
>
> child = ChildClass(arg1, arg2)
>
> and arg1, arg2 will be passed through to the 'constructor' of the
> antecedent ParentClass (there being no overrriding __init__ method
> defined for ChildClass) and mapping to keyword1, keyword2 etc.
>
> Have I understood this correctly?


Yes, but...

The nice things about Python is that you can use the interactive 
interpreter to test such things in an instant.  (And not have to wait 
for a response from python-list.  Like this:


 >>> class ParentClass(object):
...   def __init__(self, keyword1, keyword2):
...     print 'ParentClass.__init__ called with', keyword1, keyword2
...
 >>> class ChildClass(ParentClass):
...  pass
...
 >>> child = ChildClass(123,456)
ParentClass.__init__ called with 123 456
 >>>


Gary Herron





More information about the Python-list mailing list