Super strings

The following example class includes a method that overrides Python's builtin

_str_() method. It checks whether one or two names were passed and returns the names in first name-last name order:

class Employee:

def init (self, lastname, firstname=


self.lastname = lastname

self.firstname = firstname

def str (self):

if self.firstname:

return "%s %s" % (self.firstname,



return self.lastname

When you create instances of this class and print them, the behavior of str() changes. (The print command calls str( object).)


>>> print b Stef Maruch >>> print c Maruch, Stef

Was this article helpful?

0 0

Post a comment