[Tutor] Basic class inheritance
Kent Johnson
kent37 at tds.net
Thu Jul 28 17:00:48 CEST 2005
Negroup - wrote:
> I have this class:
>
>>>>class A:
>
> ... def __init__(self, blank=False, editable=True, name='foo'):
> ... self.blank = blank
> ... self.editable = editable
> ... self.name = name
> ...
>
>>>>a = A()
>>>>a.blank, a.editable, a.name
>
> (False, True, 'foo')
>
> All as expected.
>
> Now I want that another class, call it B, inherits all
> behaviours/attributes except for the attribute blank, that now I want
> to be False.
>
> This should be possible overriding __init__ method no?
>
>>>>class B(A):
>
> ... def __init__(self, blank=True, editable=True, name='foo'):
> ... self.blank = blank
> ... self.editable = editable
> ... self.name = name
> ...
>
>>>>b = B()
>>>>b.blank, b.editable, b.name
>
> (True, True, 'foo')
>
> However, is it possible to achieve this without rewrite the whole
> __init__ method, but just overriding parts of it?
The usual way to do this is to forward to the __init__() method of the superclass for the common part. In your case you are just specializing the default arguments so all you have to do is pass the args to A.__init__():
class B(A):
def __init__(self, blank=True, editable=True, name='foo'):
A.__init__(self, blank, editable, name)
Kent
More information about the Tutor
mailing list