Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1
>>> def hello_english(Name):
... print "Hello, " + Name + "!"
...
>>> def hello_hungarian(Name):
... print "Szia, " + Name + "!"
...
>>> hello = hello_hungarian
>>> hello("Paul")
Szia, Paul!
>>> hello = hello_english
>>> hello("Paul")

Notice that function definitions include no type information. Functions are
typeless, as mentioned previously. The upside of this is that you can write one
function to do several things:


Click here to view code image





def concat(First, Second):
... return First + Second
...
concat(["python"], ["perl"])
['python', 'perl']
concat("Hello, ", "world!")'Hello, world!'





This example demonstrates how the return statement sends a value back to
the caller and also how a function can do one thing with lists and another
thing with strings. The magic here is being accomplished by the objects. You
write a function that tells two objects to add themselves together, and the
objects intrinsically know how to do that. If they do not—if, perhaps, the user
passes in a string and an integer—Python catches the error for you. However,
it is this hands-off, “let the objects sort themselves out” attitude that makes
functions so flexible. The concat() function could conceivably
concatenate strings, lists, or zonks—a data type someone created herself that
allows adding. The point is that Python does not limit what your function can
do. Tacky as it might sound, the only limit is your imagination.


Object Orientation


After having read this far, you should not be surprised to hear that Python’s
object orientation is flexible and likely to surprise you if you have been using
C-like languages for some time.


The best way to learn Python object-oriented programming (OOP) is to just
do it. Here is a basic script that defines a class, creates an object of that class,
and calls a function:


Click here to view code image

Free download pdf