Objetos - johncroth/pythonEd2024 GitHub Wiki

We have just learned about how to call and create functions, but there is another way to call functions in Python that is very fundamental and very common, ad it is time to learn it. To talk about this, we need to discuss the concept of objects in Python.

Save and execute the program below as objectos_a.py:

amigos = [ "angela", "dolores", "beto" ]
otras = [ "xavier", "yuri" ]
print( amigos )
print( otras )
amigos.append( "carlos" ) 
print( amigos)
print( otras )

Of course, this program defines 2 variables personas and otras with a list of names, prints out the lists, adds the name "carlos" to that and prints out value of the revised lists. (We have actually used this append function before.) What is this append function? Well, append is a function that "belongs" to a particular list, and the line amigos.append( "carlos" ) says "add "carlos" to the list amigos." We have another list otras but that is not affected by amigos.append( "carlos" ).

If we want to append a name to otras we do that like this: (add the following lines to objectos_a.)

otras.append( "zina" )
print( personas )
print( otras )

You can see that the program adds "carlos" to amigos and "zina" to otras." The function amigos.append only changes the list in amigos, and otras.append only affects the list in otras. We say the function append acts to a particular list, the list named to the left of the .append.

There are lots of functions on lists

There are many ways that we might want to change a list, and there are a lot of functions belonging to lists that we can use

amigos = [ "angela", "dolores", "beto" ]
amigos.insert( 1, "miguel" )
print( amigos )
amigos.sort()
print( amigos )
amigos.reverse()
print( amigos )

Two turtles

This

But Why? (Optional)

Why do this thing with the dot . as in amigos.append("carlos") above? Well, what's the alternative? We could define a function:

def append( lista, cosa ):
    # adjuntar cosa a lista en alguna manera

However, there are actually other things besides list we would like to append to (strings of characters, files, dictionaries, and more.) So it would have to be more like

def append_a_lista( lista, cosa):
    # ajuntar cosa a lista en alguna manera

def append_a_cadena( cadena, cosa):
    # algo asi

And so on. But, it is obvious from amigos.append("carlos") that we are appending to a certain list, and from "letras".append( "x")

The big question

Is how can you write a function in this style? The answer is a bit complicated.