Inner class function without self

后端 未结 5 1673
栀梦
栀梦 2021-01-02 03:03

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         


        
5条回答
  •  独厮守ぢ
    2021-01-02 03:59

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

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

    [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
    

    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.

    [Emphasis mine]

提交回复
热议问题