0

I wrote a simple script:

class A:
    def print1(self):
        print(self)

    @staticmethod
    def print2(thing):
        print(thing)

A.print1('123')
A.print2('123')

print(A.print1)
print(A.print2)

And the output is:

123
123
<function A.print1 at 0x7f2f4a1778c8>
<function A.print2 at 0x7f2f4a17b510>

First YES or NO: Seems for now A.print1 and A.print2 do all same on functional, right?

As code from Python on Github:

/* Bind a function to an object */
static PyObject *
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
{
    if (obj == Py_None || obj == NULL) {
        Py_INCREF(func);
        return func;
    }
    return PyMethod_New(func, obj);
}

And Python version StaticMethod from Descriptor HowTo Guide

class StaticMethod(object):
    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, objtype=None):
        return self.f

Second YES or NO: Does A.print1 and A.print2 all just get a function very same like print_pure which defined below, right?

def print_pure(thing):
    print(thing)
1
  • 1
    That's a yes. The way you are using the methods, they are all just functions. Commented Apr 9, 2019 at 8:00

1 Answer 1

2

If you are going to invoke the methods from the class itself like you are doing in your code, "YES" there is no difference. However things will start to differ the moment you start invoking these methods with the object of the class.

Bound Method or Instance method is a function which is tied to the object of the class and would always require a reference to the object of the class as its first argument.

Class method is a function which is tied to the class itself and would always require a reference to the class itself as its first parameter.

Static methods are the one which are neither tied to the class nor the object of the class.

Even with your code if I do like this.

a = A()
a.print2('123') # this will work just fine, since this is a static method
a.print1('123')  # this will give me the TypeError print1() takes 1 positional argument but 2 were given 

Since print1 is a instance or bound method so when this method is called with object of the class a in this case, it requires the first parameter as the reference to the object. This reference is passed implicitly when you call the method with the object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.