What is a class member? What is a method?

It seems like an acceptable answer to the question

What is a method?

there is

A method is a function that is a member of a class.

I do not agree with that.

class Foo(object): pass def func(): pass Foo.func = func f = Foo() print "fine so far" try: f.func() except TypeError: print "whoops! func must not be a method after all" 
  • Is func member of Foo ?
  • Is func method Foo ?

I am well aware that this will work if func has a self argument. It is obvious. I am wondering if he is a member of Foo even if it is represented as a method .

0
python
Sep 24 '10 at 23:09
source share
3 answers

You just check it wrong:

 >>> class Foo(object): pass ... >>> def func(self): pass ... >>> Foo.func = func >>> f = Foo() >>> f.func() >>> 

You mistakenly forget that the def self argument has absolutely nothing to do with f.func , the "non-method", of course. The peculiar vanity of having def outside the class instead of it (completely legal Python, of course, but, as I said, peculiar) has nothing to do with it: if you forget to have the first argument (conditionally named self ) in your def statements for methods, you will get errors when called, of course (a TypeError is what you get, among other things, whenever the actual arguments specified in the call can't match the formal arguments accepted by def , of course).

+6
Sep 24 '10 at 23:26
source share

A type error will not be selected if func has a self argument, like any other instance method.

This is because when you evaluate f.func , you actually bind f to the first argument of the function - then it becomes a private application, which you can provide with additional arguments.

If you want this to be a static method, you need a staticmethod decorator that simply discards the first parameter and passes the rest to the original function.

So, 2 ways to make it work:

 def func(self): pass 

- or -

 Foo.func = staticmethod(func) 

depending on what you are striving for.

+1
Sep 24 '10 at 23:35
source share

As written, func is a member of Foo and a method of Foo instances such as your f. However, it cannot be called successfully because it does not accept at least one argument.

func is in the namespace f and has a _call_ () method. In other words, the method that Python tries to call it as one is enough when you call it as one. If he shakes like a duck, in other words ...

To prevent this challenge, either here or there, in my opinion.

But perhaps the correct answer is "But the doctor! When I do not accept any arguments in the function defined in the class, I am embarrassed about whether this is a method or not." just β€œdon't do it” :-)

0
Sep 25 '10 at 1:01
source share



All Articles