This won't work if you instantiated without keyword arguments:
BClass('a', 'b')
It'll fail since it'll populate 'arg3' and 'arg4', leaving both 'args' and
'kwargs' empty when passed to the AClass's __init__. The BClass definition
also allows no arguments to be passed (since arg3 and arg4 have default
values defined for them), which will again fail since AClass requires arg1
and arg2 (no default values).
There isn't really one way of solving this, it depends a lot on the
situation and how these classes relate to each other. Sometimes it's best to
keep the function definition in sync, only [explicitly] adding new
parameters on the derived classes; sometimes it's better to use *kwargs (and
not *args), and then having the different classes pick out the parameters
they need from kwargs (*args would be much harder to manage);
- Ofer
www.mrbroken.com
On Wed, Oct 27, 2010 at 4:55 AM, Erkan Özgür Yılmaz <[email protected]>wrote:
> Hi Everybody,
>
> It's a little bit, not too much but little out of the scope of this group
> but I need the comments of experienced Python developers for that;
>
> Ok, now I'm developing something big, big enough that I need to use heavy
> inheritance in my classes. So I have, lets say 2-3 levels of inheritance in
> some classes (yeah I know it is not that big for now :) ). My problem is
> about the arguments of the classes. Because I'm adding new arguments in
> every level of inheritance, I came across a problem of repeating the
> arguments in every class that inherits from another class and found a
> solution, it is working but I want to be sure about it is Pythonic enough
> and correct to use something like this.
>
> Lets say I have a base class called AClass like this:
>
> class AClass(object):
> def __init__(self, arg1, arg2):
> print arg1, arg2
>
> just for testing purposes I've added print statements to see if it is
> working fine.
>
> And another class which derives from AClass and it adds a couple of
> arguments to the __init__:
>
> class BClass(AClass):
> def __init__(self, arg3=None, arg4=None, *args, **kwargs):
> super(BClass,self).__init__(*args, **kwargs)
> print arg3, arg4
>
> so my question is, is it good/safe/nice to use *args, **kwargs and pass
> them to the super of BClass to avoid repeating the arguments of the parent
> class (AClass)?
>
> I've tested the classes with this:
>
> >>> aBObj = BClass(arg1='arg1_test', arg2=10, name='ozgur', email='
> [email protected]')
>
> # prints out this
> arg1_test 10
> ozgur [email protected]
>
> so it is working, but again is it nice to do that?
>
> thank you already for your answers...
>
> E.Ozgur Yilmaz
> Lead Technical Director
> eoyilmaz.blogspot.com
> www.ozgurfx.com
>
> --
> http://groups.google.com/group/python_inside_maya
--
http://groups.google.com/group/python_inside_maya