【问题标题】:How are methods, `classmethod`, and `staticmethod` implemented in Python?Python 中的方法、`classmethod` 和 `staticmethod` 是如何实现的?
【发布时间】:2011-10-04 20:11:31
【问题描述】:

Python 中的方法在什么时候获取get 属性? ——只要在课堂上定义它们?为什么 Python 让我定义一个没有任何参数的方法(甚至不是第一个 self 参数)?

我知道如何使用classmethodstaticmethod,而且我知道它们是内置函数,但是这样修饰的函数会发生什么?

基本上,我想知道类定义和类构造之间发生的“魔法”。

【问题讨论】:

    标签: python class methods built-in


    【解决方案1】:

    看看这个。

    http://docs.python.org/howto/descriptor.html#static-methods-and-class-methods

    您还可以查看 funcobject.c 中的类和静态方法对象的源代码:

    http://hg.python.org/cpython/file/69b416cd1727/Objects/funcobject.c

    类方法对象定义从第 694 行开始,而静态方法对象定义从第 852 行开始。(当 methodobject.c 也存在时,他们在 funcobject.c 中有标题为“method”的项目,我确实觉得很有趣。)

    【讨论】:

      【解决方案2】:

      供参考,来自@JAB 的回答中的the first link

      使用非数据描述符协议,纯 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
      

      ...

      使用非数据描述符协议,纯 Python 版本的 classmethod() 将如下所示:

      class ClassMethod(object):
          "Emulate PyClassMethod_Type() in Objects/funcobject.c"
      
          def __init__(self, f):
              self.f = f
      
          def __get__(self, obj, klass=None):
              if klass is None:
                  klass = type(obj)
              def newfunc(*args):
                  return self.f(klass, *args)
              return newfunc
      

      【讨论】:

        猜你喜欢
        • 2012-07-30
        • 1970-01-01
        • 2021-08-14
        • 1970-01-01
        • 2019-08-14
        • 2020-04-11
        • 1970-01-01
        • 2019-04-28
        • 2018-04-15
        相关资源
        最近更新 更多