没有自我的内在功能 [英] Inner class function without self

查看:59
本文介绍了没有自我的内在功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家和平!
我正在使用Python 3.6.3,但我发现奇怪的是这样的构造是可能的:

Peace, everyone! I'm using Python 3.6.3 and I find strange that such construction is possible:

class TestClass(object):
    def __init__(self):
        self.arg = "arg"

    def test():
        print("Hey test")

并使用:

>>> TestClass.test()
"Hey test"

我知道在Python中有标准以 self 作为参数(不知道如何正确调用)的方法,静态方法,类方法,抽象方法。

I know that in Python there are standard methods with self as parameter (don't know how to call them properly), static methods, class methods, abstract methods.

但是 test()是哪种方法?
是静态方法吗?

But what kind of method the test() is? Is it static method?

已编辑:

在类中确定函数的方法是否有有用的用例?

Are there any useful usecases of such method of determining a function inside a class?

推荐答案

在Python 3中,(不同于Python 2)从类访问和调用的函数只是另一个函数;没什么特别的:

In Python 3, (unlike Python 2) a function accessed and called from the class is just another function; nothing special:


请注意,每次从功能对象到实例方法
对象的转换都会发生

[ Emphasis mine ]

您只是偶然通过正确的参数集调用了函数,尽管可以通过类对象进行访问。与通过实例为该方法调用基础函数对象相同:

You just happened to be calling the function with the right set of parameters albeit accessed via the class object. Same as calling the underlying function object for the method via an instance:

TestClass().test.__func__() # "Hey test"

快速测试可以进一步解释:

A quick test explains it further:

print(TestClass().test is TestClass.test)
# False
print(TestClass().test.__func__ is TestClass.test)
# True

但是,在Python 2中,行为从函数对象到对象的转换是不同的方法对象在通过类或实例访问属性时发生:

However, in Python 2, the behaviour is different as the transformation from function object to method object happens when the attribute is accessed via both the class or instance:


请注意,函数的转换每次从类或实例的
中检索属性时,都会发生对象对象(未绑定或绑定到
)的方法对象。

Note that the transformation from function object to (unbound or bound) method object happens each time the attribute is retrieved from the class or instance.

[重点矿]

这篇关于没有自我的内在功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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