Popular style document?
Michael Chermside
mcherm at destiny.com
Fri Mar 22 13:22:11 EST 2002
> If you mean requirement to say def meth(something, arg) instead of def
>> meth(arg), compiler does not necesarily know when compiling whether
>> function will be used as method or not. (Methods can be defined
>> outside of class statement and assigned as method later.)
>
> Yes, this is what I meant. How does this work though, when assigning a
> method to a class? I mean, let's say that you have a method taking two
> arguments, concatenate (x, y). When assigning this method to a class,
> will that mean that the first argument is always replaced by the class
> instance, so I'd have to call it like this: aclass.concatenate (y), and
> the first argument, x, will always correspond to aclass?
Yes.
Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> class MyClass: # CREATE A CLASS
pass
>>> def concatenate(x, y): # CREATE A FUNCTION
print 'concatenating %s and %s' % (x,y)
return [x, y]
>>> MyClass.concatenate = concatenate # MAKE THE FUNC A METHOD!
>>> myInstance = MyClass() # NEED AN INSTANCE
>>> myInstance.concatenate(7) # CALL METHOD ON THE INSTANCE
concatenating <__main__.MyClass instance at 0x009557A8> and 7
[<__main__.MyClass instance at 0x009557A8>, 7]
More information about the Python-list
mailing list