[Tutor] methods and functions
Lloyd Kvam
lkvam@venix.com
Wed Jun 18 17:41:22 2003
printIt is a method. name is an attribute of class A instances.
>>> a.name(b)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: 'str' object is not callable
We can try this:
>>> a.name = b
>>> a.printIt()
<__main__.B instance at 0x013B0EA0>
The name attribute of a is no longer a string. When python
tries to print it, it uses its default machinary to turn that
instance of the B class into a string and then prints the
result.
PrintIt could be written as a regular old function outside the class.
def printIt(arg):
print arg.name
I changed self to arg simply because there is no longer a self concept. self
would still be valid Python syntax.
>>> a=A('Aay')
>>> printIt(a)
Aay
>>> printIt(b)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "E:\ptg\campgrnd\Script1.py", line 13, in printIt
print arg.name
AttributeError: B instance has no attribute 'name'
the class A __init__ provided a name attribute for each instance. The B
instances are missing that attribute. So printIt is only usefule when it's
argument has a name attribute. Keeping printIt part of the A class makes
it difficult to pass in an argument that will not work.
HTH
Gerardo Arnaez wrote:
> --- Lloyd Kvam <pythontutor@venix.com> wrote:
> A method is essentially a function
>
>>defined within a class body.
>
>
> Than is an instance method just passing an some other
> class instace thorught another class instances' method
>
> ie
>
> class A:
> def __init__ (self,A):
> self.name=A
>
> def printIt(self):
> print self.name
>
> class B:
> def __init__ (self):
> pass
>
>
> a=A('Aay')
> b=B()
>
> a.name
> 'Aay'
>
> a.printIt
> 'Aay'
>
> So what does
>
> a.name(b) do?
> Is this an instance method?
>
> Is how a method differs from a function?
>
>
> G
>
>
>
>
>
>
> __________________________________
> Do you Yahoo!?
> Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
> http://calendar.yahoo.com
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-443-6155
fax: 801-459-9582