加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:35:30 所属栏目:Python 来源:网络整理
导读:和平,大家好! 我正在使用 Python 3.6.3,我发现这样的构造是可能的奇怪: class TestClass(object): def __init__(self): self.arg = "arg" def test(): print("Hey test") 并使用: TestClass.test()"Hey test" 我知道在Python中有标准方法,其中self作为参
和平,大家好!
我正在使用 Python 3.6.3,我发现这样的构造是可能的奇怪:
class TestClass(object):
    def __init__(self):
        self.arg = "arg"

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

并使用:

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

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

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

编辑:

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

解决方法

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

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.

[强调我的]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读