method overriding trick

Darrell news at dorb.com
Sun Nov 14 01:53:29 CET 1999


Eric Jacobs <x at x.x> wrote in message news:382DFF59.51F186A6 at x.x...
> You wouldn't be able to reassign the _Parent variable to define another
> class elsewhere in the same module, though, because the functions defined
> this way will always look up the _Parent from the module namespace at
> execution time. A variant that removes that restriction is:
>
> > _Parent = basedlg.BaseDlg
> > class AddressDlg(_Parent):
> >     def __init__(self, param, _Parent=_Parent):
>
> The default args are evaluated at function definition time, which means
> that the variable has the value you expect. Now you have true cut'n'paste
> coding!

This doesn't seem to be a problem.

>>> class A:
...     a=1
...
>>> class C:
...     pass
...
>>> p=A
>>> class B(p):
...     def __init__(self, p=p):
...             print 'p:', p
...             print self.__class__.__bases__
...
>>> B().a
p: __main__.A
(<class __main__.A at 7f8f00>,)
1
>>> p=C
>>> B().a
p: __main__.A
(<class __main__.A at 7f8f00>,)
1
>>>

If you want to change base classes on the fly check this out.

>>> class X:
...     pass
...
>>> X.__bases__
()
>>> X.__bases__=(B,)
>>> X()
p: __main__.A
(<class __main__.B at 7fb760>,)
<__main__.X instance at 7fb1f0>
>>>

--
--Darrell






More information about the Python-list mailing list