如何在Python中实现方法,类方法和静态方法? [英] How are methods, `classmethod`, and `staticmethod` implemented in Python?

查看:61
本文介绍了如何在Python中实现方法,类方法和静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中的方法在什么时候获取get属性? —一旦在班级中定义了它们?为什么Python让我定义一个没有任何参数(甚至没有第一个self参数)的方法?

At what point do methods in Python acquire a get property? —As soon as they're defined in the class? Why does Python let me define a method without any arguments (not even a first self argument)?

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

I know how to use classmethod and staticmethod, and I know that they're built-in functions, but what happens to a function that is so-decorated?

本质上,我想知道类定义和类构造之间发生的魔术".

Essentially, I'm wondering about the "magic" that happens between class definition and class construction.

推荐答案

检查一下.

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

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

You can also take a look at the source code for class and static method objects, in funcobject.c:

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

类方法对象定义从第694行开始,而静态方法对象定义从第852行开始.(我确实发现,当methodobject.c也存在时,它们在funcobject.c中具有名为"method"的项有点可笑.)

Class method object definition starts on line 694, while static method object definition starts on line 852. (I do find it kind of funny that they have items titled "method" in funcobject.c when methodobject.c also exists.)

这篇关于如何在Python中实现方法,类方法和静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆