Inner class function without self

后端 未结 5 1672
栀梦
栀梦 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

    TestClass.test() call actually executes the test() on the class object. This is similar to a @staticmethod (a method that can be executed on the class object, without creating an object first).

    ins = TestClass()
    ins.test()
    

    will throw an exception, since instance methods pass self as the first argument, and test() takes no args.

    When an object is created, the methods defined in the clas are bound to it. They are actually different objects, hence they have different ids:

       id(TestClass.test)
    => 140288592901800
       obj = TestClass()
       id(obj.test)
    => 140288605765960
    

    In Python 2.7, your code throws an exception which is self explantory:

    Traceback (most recent call last):
      File "", line 1, in 
        TestClass.test()
    TypeError: unbound method test() must be called with TestClass instance as 
    first argument (got nothing instead)
    

提交回复
热议问题