why i love python...

Philip Swartzleonard starx at pacbell.net
Thu Feb 7 01:38:55 EST 2002


Mark McEahern || Wed 06 Feb 2002 05:34:52p:

> [please forgive the embedded html; this is posted on my weblog, but
> since that's not exclusively about python, i didn't want to bore you
> all with it.] 
> 
> what started out as just an attempt to make debugging easier turned
> into an epiphany about why i love python.  allow me to share that
> love... 
> 
> python comes with a slew of special methods for objects that you can
> leverage to do some really neat things.  consider __str__, which is
> called on your objects when you <b>print</b> them.  if you don't define
> __str__, that's ok, you'll get something like this:
> 
> <pre>
>>>>class Simple:pass ...
>>>> s = Simple()
>>>> print s
> <__main__.Simple instance at 0x100fd4c8>
> </pre>
> 
> by defining __str__, i get to control the output generated by print
> (and str()):
> 
> <pre>
>>>> class Prints:
> ...     def __str__(self):
> ...             return "whatever i like"
> ...
>>>> p = Prints()
>>>> print p
> whatever i like
> </pre>
> [further examples]

Hm, i really like this feature too. Consider this:

class Container( list ):
    """Base class for something that can contain."""
    def __repr__(self):
        """We are not a list when printed"""
        basic = object.__repr__(self)
        return basic

    def __str__(self):
        return self.printcontent()

    def printcontent(self, indent = 0):
        """Recurisve repr listing"""
        output = repr(self) + '\n'
        for x in self:
            for tabs in range(indent+1):
                output += ' '
            if hasattr( x, 'printcontent'):
                output += x.printcontent( indent+1 )
            else:
                output += repr(x) + '\n'
        return output

class Object( Container ):
    #init sets name
    def __repr__(self):
        return '<' + self.name + '>'

class Creature( Object ):
    #init sets name, class, brain
    def __repr__(self):
        return ''.join( '<', self.class, ' ', self.name,
                        ' is ', self.brain.state_desc )

    def __str__(self):
        out = ' '.join( name, " the ", class, "\nI am ",
                        self.brain.state_desc "\n")
        keys = self.stats.keys()
        keys.sort()
        for key in keys:
            out += ''.join( key, ': ', self.stats[key] '\n' )
        out += "I am carrying:\n"
        out += Object.__str__
        return out

PyFilling from PyCrust just became a lot more useful :). (My container 
already works like this, i just made up the other two, but i will probably 
do similar.)

-- 
Philip Sw "Starweaver" [rasx] :: www.rubydragon.com



More information about the Python-list mailing list