【问题标题】:What's difference between class.method class.staticmethod with same parameters?具有相同参数的 class.method class.staticmethod 有什么区别?
【发布时间】:2019-04-09 07:52:45
【问题描述】:

我写了一个简单的脚本:

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

和 Python 版本 StaticMethod 来自 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

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

def print_pure(thing):
    print(thing)

【问题讨论】:

  • 是的。你使用这些方法的方式,它们都只是函数。

标签: python function class static-methods descriptor


【解决方案1】:

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

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

类方法是一个与类本身绑定的函数,并且总是需要对类本身的引用作为其第一个参数。

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

如果我愿意,即使使用您的代码。

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 的对象调用此方法时,它需要第一个参数作为对该对象的引用。当您使用对象调用方法时,会隐式传递此引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 2020-05-25
    • 2011-07-28
    • 2014-10-06
    相关资源
    最近更新 更多