[Tutor] Python notations

Magnus Lycka magnus@thinkware.se
Tue Feb 4 10:37:03 2003


At 09:25 2003-02-04 -0400, D2 wrote:
>for example, when do i use object.method or method(parameters), or
>object.method() or something.method().other_method().something (pan)
>I didn't find something explicit to help me understand the way that works.

All calls require (). If you access a method/function without (),
you just get a reference to it back, you don't call it.

The dot-notation a.b is used to get access to an object b which
is part of an object a. The word object is used in a fairly
wide meaning in Python, far beyond an instance of a class.

Like this:

 >>> class C:
...     def m(self):
...             return "I'm a method in the class of %s" % self
...
 >>> o = C()
 >>> print o.m
<bound method C.m of <__main__.C instance at 0x06E7E810>>
 >>> print o.m()
I'm a method in the class of <__main__.C instance at 0x06E7E810>

All object references can be assigned to variables.

 >>> ref_to_method_m_of_instance_o = o.m
 >>> print ref_to_method_m_of_instance_o
<bound method C.m of <__main__.C instance at 0x06E7E810>>
 >>> print ref_to_method_m_of_instance_o()
I'm a method in the class of <__main__.C instance at 0x06E7E810>

Or:

 >>> import math
 >>> sinus = math.sin
 >>> angle = math.pi/4
 >>> sinus(angle)
0.70710678118654746
 >>> math.sin
<built-in function sin>
 >>> math.sin(angle)
0.70710678118654746

math.sin returns a reference to the sin-function, which can
be assigned to another variable, like sinus. math.sin(x) is
a function call with the parameter x.

Sometimes, a function call will return an object that can be
called. (The example below is meaningless, but there are
certainly useful applications for this...)

 >>> def returnsFunction():
...     def x(a, b):
...             return a + b
...     return x
...
 >>> x = returnsFunction()
 >>> print x(2,3)
5

Instead of using a reference to the returned function, and
call it through that reference (x above), we can call it
at once.

 >>> returnsFunction()(6,7)
13

If you see "x.y().z()" it means that you have an object x
which contains an object y that can be called. If x is a
module, y is a function or a class, and if x is an instance of
a class, y is a method of its class. The call to x.y() will
return an object z that can be called, for instance a function,
a class or an instance with a __call__ method.

E.g. if you have a module...

# x.py - a module

class y:
     def z(self):
         print "Hello"

.....

And then you use it:

 >>> import x
 >>> x.y().z()
Hello


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se