Inner class function without self

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

    Let me explain with an example:

    class TestClass(object):
      def __init__(self):
        self.arg = "arg"
    
      def test1():
        print("class method test1, Hey test")
    
      @classmethod
      def test2(cls):
        print("class method test2, Hey test")
    
      def test3(self):
        print("instance method test3, Hey test")
    

    Look what happens when you call test1 with the class or with the instance:

    First:

      TestClass.test1() #called from class
    class method test1, Hey test
       TestClass().test1() #created an instance TestClass()
    Traceback (most recent call last):
      File "python", line 1, in 
    TypeError: test1() takes 0 positional arguments but 1 was given
    

    that's because when you create an instance, the self parameter is used, but here, the method has not the self parameter, that's why it brakes.

    next one!

       TestClass.test2()
    class method test2, Hey test
       TestClass().test2()
    class method test2, Hey test
    

    That worked for instance and for class, why? well, as you can see test2(cls) take an argument, cls, here, I'm not using it, so, it's ok that it works.

    bring me the next subject, muajaja

      TestClass().test3()
    instance method test3, Hey test
       TestClass.test3()
    Traceback (most recent call last):
      File "python", line 1, in 
    TypeError: test3() missing 1 required positional argument: 'self'
    

    That's easy to see, when you call it as class, you haven't provided the self parameter

提交回复
热议问题