[Tutor] Why are arguments sometimes on the left side?

Alex Hall mehgcap at gmail.com
Mon Sep 20 17:00:46 CEST 2010


On 9/20/10, Michael Scharf <mnshtb at gmail.com> wrote:
> Hi,
>
>
> Why is it
>
>
>
>    list0.extend(list1)
>
>
>
> and not
>
>
>    extend(list 0, list1)
>
>
>
> or
>
>
>    stri0 = stri0.strip()
>
>
> and not
>
>
>    stri0 = strip(stri0)

This is because you are calling methods on objects, in this case
strings and lists. You create a list, then want to extend it with
another list. Think of it as operating on list0, so, to operate on it,
you call one of its functions (extend). Some functions do not work
this way, such as print, since print is not a function under an object
or class. If I create a dog class, then create Fluffy as an object:
class dog(object):
 def __init__(self, name):
  self.name=name
 def bark(self):
  print("bark")

f=dog("Fluffy")

Okay, we now have a dog named Fluffy, which is just one instance of
our dog class. With the way you would want to do things, I would have
to say
bark(f)
But what is bark? Where is it defined? You can see it is in the dog
class, but Python cannot; you passed a dog instance to bark(), but
that will not tell Python to search in the dog class to find the bark
method. Saying
f.bark()
will work since it tells Python:
take this instance of dog, called f, and call its bark method. The
bark method is in the dog class since bark is being called on a dog
object (remember that an object is just an instance of a class).
I hope this made some sense.
>
>
>
> Why have arguments on the left side at all, when usually the dot notation
> left to right implies a hierarchical relation: file.class or class.method
> etc.
Exactly: list.function (such as list0.extend) is just the same as
class.function, since a list is a class and list0 is an instance of
the list class, so you are just calling list's extend function on a
particular list, list0 in this case.
>
>
>
> I googled this, but didn’t find it.
>
>
>
> Thank you,
>
> Mike
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


More information about the Tutor mailing list