Defining classes

Michael Spencer mahs at telcopartners.com
Wed Dec 13 18:24:14 EST 2006


Nick Maclaren wrote:
> 
> Well, I am already doing that, and regretting the fact that Python
> doesn't seem to allow a class instantiation to return a new class :-)
> 

  >>> class Fake(object):
  ...     def __new__(cls):
  ...         return 42
  ...
  >>> Fake()
  42
  >>>

"instantiation" (i.e., calling the __new__ method) of new-style classes 
can return whatever you like, but I'm not sure how that helps.

One way of having a class member refer to the class, is to use the 
descriptor protocol, e.g.,:

  >>> def brinjal(cls): return cls.__name__
  ...
   >>> class Brinjal(object): # must be new-style
  ...     def __get__(self, obj, cls):
              return brinjal(cls)

  ...
  >>> class Weeble(object): # should be new-style
  ...     wumpus = Brinjal()
  ...
  >>> Weeble.wumpus
  'Weeble'
  >>> Weeble().wumpus
  'Weeble'
  >>>


Michael




More information about the Python-list mailing list