Class method differences in Python: bound, unbound and static

后端 未结 13 1258
日久生厌
日久生厌 2020-11-22 08:54

What is the difference between the following class methods?

Is it that one is static and the other is not?

class Test(object):
  def method_one(self)         


        
13条回答
  •  爱一瞬间的悲伤
    2020-11-22 09:41

    When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable self actually means nothing, it's just a coding convention. You could call it gargaloo if you wanted. That said, the call to method_two would raise a TypeError, because Python is automatically trying to pass a parameter (the reference to its parent object) to a method that was defined as having no parameters.

    To actually make it work, you could append this to your class definition:

    method_two = staticmethod(method_two)
    

    or you could use the @staticmethod function decorator.

提交回复
热议问题