Inner class function without self

后端 未结 5 1689
栀梦
栀梦 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:42

    In python 3, there is no difference between a function and a function defined in a class:

    def test():
        print("Hey test")
    
    class TestClass:
        def test():
            print("Hey test")
    
    test() # works
    TestClass.test() # also works
    

    Both of these are normal functions.

    The magic of the implicit self argument happens when you access a function through an instance of the class, like this:

    obj = TestClass()
    obj.test() # throws an error because the test function doesn't accept arguments
    

    This is when the function test is turned into the (bound) method test. You can see the difference if you print them:

    print(TestClass.test) 
    print(instance.test)
    # output:
    # 
    # >
    

    To sum it up:

    • Accessing a function through the class gives you the original function.
    • Accessing a function through an instance gives you a method with a bound self argument.

    For details about how exactly this conversion from function to bound method works, see the descriptor how-to, and specifically the section about functions.

提交回复
热议问题