参数相同的class.method class.staticmethod有什么区别?

2024-09-29 05:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个简单的脚本:

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)

输出为:

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

首先是或否:现在看来A.print1A.print2在函数上都是一样的,对吗

作为Github上Python的代码:

/* 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);
}

以及来自Descriptor HowTo Guide的Python版本StaticMethod

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

第二个是或否:A.print1A.print2是否都得到了一个与下面定义的print_pure非常相似的函数,对吗

def print_pure(thing):
    print(thing)

Tags: 函数selfobjreturnobjectdeffunctionat
1条回答
网友
1楼 · 发布于 2024-09-29 05:24:27

如果要像在代码中那样从类本身调用方法,“YES”没有区别。但是,当您开始用类的对象调用这些方法时,情况就会有所不同

绑定方法或实例方法是一个绑定到类的对象的函数,并且始终需要引用类的对象作为其第一个参数

类方法是一个绑定到类本身的函数,它总是需要引用类本身作为其第一个参数

静态方法既不与类绑定,也不与类的对象绑定

即使是你的代码,如果我这样做

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 

由于print1是一个实例或绑定方法,因此在这种情况下,当使用类a的对象调用此方法时,它需要第一个参数作为对对象的引用。当用对象调用方法时,隐式传递此引用

相关问题 更多 >