What does it mean by the 'super object returned is unbound' in python?

前端 未结 4 1313
轻奢々
轻奢々 2021-02-05 21:34

According to http://docs.python.org/2/library/functions.html#super,

If the second argument is omitted, the super object returned is unbound.

4条回答
  •  执念已碎
    2021-02-05 21:49

    Other answers (answer, answer) for your question already explained the meaning of the words bound / unbound.

    So my focus is to explain only the use of an unbound proxy object returned from the super() function (i.e. in the case it was used only with 1 argument).

    The reason for obtaining an unbound object is to bind it later.

    Particularly, for the unbound object returned from the super() function you may bind it to an appropriate object using its __get__() method, e.g.

    super(C).__get__(c)        # where C is a class and c is an object
    

    To illustrate it, let's create 3 dependent classes and 3 objects - one for every class:

    class A:
        def __init__(self, name):
            self.name = name
        def message(self, source):
            print(f"From: {source}, class: A, object: {self.name}")
    
    class B(A):
        def __init__(self, name):
            self.name = name
        def message(self, source):
            print(f"From: {source}, class: B, object: {self.name}")
    
    class C(B):
        def __init__(self, name):
            self.name = name
        def message(self, source):
            print(f"From: {source}, class: C, object: {self.name}")
    
    a = A("a")
    b = B("b")
    c = C("c")
    

    Now in the interactive console, at first for understanding things:

    >>> super(B)                  # unbounded (note 'None')
    
    
    >>> super(B).__get__(b)       # bounded to object b (note address)
    >
    
    >>> b                         # note: the same address
    '<__main__.B at 0xa9bdac0>
    

    then — to show results of using different combinations of classes / objects
    (in our case for delegating the method .message()):

    >>> super(B).__get__(b).message("super(B)")
    From: super(B), class: A, object: b
    
    >>> super(C).__get__(c).message("super(C)")
    From: super(C), class: B, object: c
    
    >>> super(B).__get__(c).message("super(C)")
    From: super(C), class: A, object: c
    

    and finally examples for binding and unbound proxy to appropriate classes:

    >>> A.name = "Class A"            # Preparing for it - 
    >>> B.name = "Class B"            # creating some class attributes
    
    >>> super(B).__get__(B).name      # Proxy super(B) bounded to class B
    'Class A'
    
    >>> super(B).__get__(C).name      # Proxy super(B) bounded to class C
    'Class A'
    
    >>> super(C).__get__(C).name      # Proxy super(C) bounded to class C
    'Class B'
    

提交回复
热议问题