[Tutor] Python notations

D2 borelan@wanadoo.fr
Tue Feb 4 13:26:32 2003


Many thanks, Magnus,

That's a thorough explanation.

It will be easier to read Zope's code.

Andre

Magnus Lycka a =E9crit:
> At 09:25 2003-02-04 -0400, D2 wrote:
>=20
>> 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=20
>> works.
>=20
>=20
> All calls require (). If you access a method/function without (),
> you just get a reference to it back, you don't call it.
>=20
> 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.
>=20
> Like this:
>=20
>  >>> class C:
> ...     def m(self):
> ...             return "I'm a method in the class of %s" % self
> ...
>  >>> o =3D 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>
>=20
> All object references can be assigned to variables.
>=20
>  >>> ref_to_method_m_of_instance_o =3D 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>
>=20
> Or:
>=20
>  >>> import math
>  >>> sinus =3D math.sin
>  >>> angle =3D math.pi/4
>  >>> sinus(angle)
> 0.70710678118654746
>  >>> math.sin
> <built-in function sin>
>  >>> math.sin(angle)
> 0.70710678118654746
>=20
> 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.
>=20
> 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...)
>=20
>  >>> def returnsFunction():
> ...     def x(a, b):
> ...             return a + b
> ...     return x
> ...
>  >>> x =3D returnsFunction()
>  >>> print x(2,3)
> 5
>=20
> Instead of using a reference to the returned function, and
> call it through that reference (x above), we can call it
> at once.
>=20
>  >>> returnsFunction()(6,7)
> 13
>=20
> 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.
>=20
> E.g. if you have a module...
>=20
> # x.py - a module
>=20
> class y:
>     def z(self):
>         print "Hello"
>=20
> .....
>=20
> And then you use it:
>=20
>  >>> import x
>  >>> x.y().z()
> Hello
>=20
>=20


--=20
Andre