Class method differences in Python: bound, unbound and static

后端 未结 13 1277
日久生厌
日久生厌 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 09:43

    >>> class Class(object):
    ...     def __init__(self):
    ...         self.i = 0
    ...     def instance_method(self):
    ...         self.i += 1
    ...         print self.i
    ...     c = 0
    ...     @classmethod
    ...     def class_method(cls):
    ...         cls.c += 1
    ...         print cls.c
    ...     @staticmethod
    ...     def static_method(s):
    ...         s += 1
    ...         print s
    ... 
    >>> a = Class()
    >>> a.class_method()
    1
    >>> Class.class_method()    # The class shares this value across instances
    2
    >>> a.instance_method()
    1
    >>> Class.instance_method() # The class cannot use an instance method
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead)
    >>> Class.instance_method(a)
    2
    >>> b = 0
    >>> a.static_method(b)
    1
    >>> a.static_method(a.c) # Static method does not have direct access to 
    >>>                      # class or instance properties.
    3
    >>> Class.c        # a.c above was passed by value and not by reference.
    2
    >>> a.c
    2
    >>> a.c = 5        # The connection between the instance
    >>> Class.c        # and its class is weak as seen here.
    2
    >>> Class.class_method()
    3
    >>> a.c
    5
    

提交回复
热议问题