您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 没有自我的内部类函数

5b51 2022/1/14 8:23:14 python 字数 3156 阅读 592 来源 www.jb51.cc/python

和平,大家好! 我正在使用 Python 3.6.3,我发现这样的构造是可能的奇怪: class TestClass(object): def __init__(self): self.arg = "arg" def test(): print("Hey test") 并使用: >>> TestClass.test() "Hey test" 我知道

概述

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

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

并使用:

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

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

但是test()是什么样的方法
这是静态方法吗?

编辑:

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

Note that the transformation from function object to instance method
object happens each time the attribute is retrieved from the instance.

[强调我的]

您恰好使用正确的参数集调用函数,尽管通过类对象访问.与通过实例调用方法的基础函数对象相同:

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

快速测试进一步解释:

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

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

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.

[强调我的]

总结

以上是编程之家为你收集整理的python – 没有自我的内部类函数全部内容,希望文章能够帮你解决python – 没有自我的内部类函数所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶