2007-09-11

Hello Python

Hello Python, this is derived from "Ruby in 20 Minutes"1

Enter the python interpreter.
---------------------------------
Define a function that says 'hello world'.
>>> def h():
... print "hello world"
...
>>> h()
hello world
Define a slightly more complex function that says hello to the passed name.
>>> def h(name):
... print "Hello %s!" % name
...
>>> h('Guido')
Hello Guido!
Define a function that says hello to the world, or to the passed name.
>>> def h(name = 'World'):
... print "Hello %s!" % name
...
>>> h()
Hello World!
>>> h('Guido')
Hello Guido!
If we want our object to remember our name, we would use a class. Enter the 'Greeter' class.
>>> class Greeter:
... def __init__(self, name = "World"):
... self.name = name
... def say_hi(self):
... print "Hello %s!" % self.name
... def say_bye(self):
... print "Goodbye %s. Please come again." % self.name
...
>>> g = Greeter('Guido')
>>> g.say_hi()
Hello Guido!
>>> g.say_bye()
Goodbye Guido. Please come again.
>>> g.name
'Guido'
>>>g.name = 'Syn'
>>> g.say_hi()
Hello Syn!
Now for fun lets write a 'MegaGreeter' that can handle multiple names.
>>> class MegaGreeter:
... def __init__(self, name = "World"):
... self.name = name
... def say_hi(self):
... if isinstance(self.name, list) or isinstance(self.name, tuple):
... for i in self.name:
... print "Hello %s!" % i
... else:
... print "Hello %s!" % self.name
... def say_bye(self):
... if isinstance(self.name, list) or isinstance(self.name, tuple):
... print "Goodbye %s. Please come again!" % ", ".join(self.name)
... else:
... print "Goodbye %s. Please come again!" % self.name
...
>>> mg = MegaGreeter(['Guido', 'Syn', 'Ninja'])
>>> mg.say_hi()
Hello Guido!
Hello Syn!
Hello Ninja!
>>> mg.say_bye()
Goodbye Guido, Syn, Ninja. Please come again!
>>> mg = MegaGreeter()
>>> mg.say_hi()
Hello World!
>>> mg.say_bye()
Goodbye World. Please come again!
>>> dir(MegaGreeter)
['__doc__', '__init__', '__module__', 'say_bye', 'say_hi']


1 comment:

MdMonk said...

Thanks for the nice little intro to classes in Python!

-Chuck