empty classes as c structs?

Carlos Ribeiro carribeiro at gmail.com
Sat Feb 5 10:05:10 EST 2005


On Sat, 05 Feb 2005 02:38:13 -0500, Leif K-Brooks <eurleif at ecritters.biz> wrote:
> Actually, in Python, class definitions are runtime executable statements
> just like any other. You can do this:
> 
>  >>> def make_class(with_spam=True):
> ...  if with_spam:
> ...   class TheClass(object):
> ...    def dostuff(self):
> ...     print 'Spam, spam, spam, spam!'
> ...  else:
> ...   class TheClass(object):
> ...    def dostuff(self):
> ...     print "I don't like spam!"
> ...  return TheClass

The real power of the class statement is that you can code it this way:

class TheClass(object):
    if with_spam:
        def dostuff(self):
            print 'Spam, spam, spam, spam!'
    else:
        def dostuff(self):
            print "I don't like spam!"

Instead of creating two classes in separate branches of the if
statement, you can as well use the if inside the class statement. It's
perfectly valid. Of course, one still has to feed it with the
'with_spam' argument - but if 'with_spam' is a global, or if the class
statement wrapped inside a function that defines 'with_spam', it will
work just as fine.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list