Proposal: default __init__

Rainer Deyke root at rainerdeyke.com
Mon Nov 13 14:21:21 EST 2000


"Andrew Dalke" <dalke at acm.org> wrote in message
news:8uotmc$uo4$1 at slb7.atl.mindspring.net...
> Hello,
>
>   I propose that objects in some Python 2.x or in 3K have a default
> __init__.  As it is now, base classes must explicitly include an
> __init__ to be future-proof, which is not obvious.  Let me explain.

Maybe the best solution is to modify attribute access for classes.  A.spam
(where A is a class) should evaluate to either A's spam attribute (if
defined), or the first spam found by searching A's bases, or, if spam is a
"special" method that can be ommited for a default behavior, a function that
provides the default behavior.  An AttributeError is raised only when none
of those exist.

This is more powerful than simple automatic methods, because it allows the
following to work correctly:

class A:
  def __init__(self):
    print "I'm not the messiah!"

class B(A):
  # No __init__ yet, but it might be added later.
  pass

class C(B):
  def __init__(self):
    B.__init__(self) # Calls A.__init__ until B gets its own __init__.
    print "He's not the messiah.  He's a very naughty boy."


If redefining attribute access for classes is impractical, then an external
function similar to getattr might be the best solution.

def getattr2(klass, name): # Utility function
  try:
    return getattr(klass, name)
  except AttributeError:
    pass
  for base in klass.__bases__:
    try:
      return getattr2(base, name):
    except AttributeError:
      pass
  raise AttributeError

def getattr3(klass, name): # The real thing.
  try:
    return getattr2(klass, name)
  except AttributeError:
    try:
      return default_methods[name]
    except KeyError:
      raise AttributeError

default_methods = {'__init__' : lambda self: None,
  '__del__' : lamda self: None,
  '__add__' : lamda self, other: other.__radd__(self),
  ...


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list