Confused with methods

From: jfj (jfj_at_freemail.gr)
Date: 02/07/05


Date: Sun, 06 Feb 2005 17:39:40 -0800
To: python-list@python.org

I don't understand.
We can take a function and attach it to an object, and then call it
as an instance method as long as it has at least one argument:

#############
class A:
   pass

def foo(x):
   print x

A.foo = foo
a=A()
a.foo()
#############

However this is not possible for another instance method:

############
class A:
  pass

class B:
  def foo(x,y)
      print x,y

b=B()
A.foo = b.foo
a=A()

# error!!!
a.foo()
##############

Python complains that 'foo() takes exactly 2 arguments (1 given)'.
But by calling "b.foo(1)" we prove that it is indeed a function which takes
exactly one argument.

Isn't that inconsistent?

Thanks,

Gerald.



Relevant Pages

  • Re: Scope of an @variable
    ... def changeName ... Each instance variable belongs to one object. ... In the top level of the class definition, ... object, but inside an instance method, it's the instance ...
    (comp.lang.ruby)
  • why descriptors? (WAS: Make staticmethod objects callable?)
    ... While I wasn't around when descriptors and new-style classes were introduced, my guess is that it's mainly because what you *usually* want when defining a function in a class is for that function to be an instance method. ... def foo: ... With a normal function ... <function foo at 0x00E69530> ...
    (comp.lang.python)
  • Re: Decorators: an outsiders perspective
    ... Paul Morrow wrote in message> class Foo: ... > def blah: # this is clearly an instance method ...
    (comp.lang.python)
  • Re: Private encapsulation question
    ... understand the reason why the last 2 method calls in the following code ... def self_n_wrapper ... Ruby implements private methods forbidding to call them with an explicit ... instance method of class B, because in the latter self is an instance of class ...
    (comp.lang.ruby)
  • Re: pondering about the essence of types in python
    ... I think the answer would be: because it's an instance method. ... By the way, Python was designed to *discourage* such behaviours, not to ... def met_stat: ...
    (comp.lang.python)