【发布时间】: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.print1 和A.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.print1 和 A.print2 是否都获得了与下面定义的 print_pure 非常相似的函数,对吗?
def print_pure(thing):
print(thing)
【问题讨论】:
-
是的。你使用这些方法的方式,它们都只是函数。
标签: python function class static-methods descriptor