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

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

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

和平,大家好!

我正在使用
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.

[强调我的]

本文来自网络,不代表青岛站长网立场。转载请注明出处: https://www.0532zz.com/html/kaifa/python/20201019/11134.html
上一篇
下一篇

作者: dawei

【声明】:青岛站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部