Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 未绑定的超级对象,超级(自我,自我)_Python_Python 3.x_Super - Fatal编程技术网

Python 未绑定的超级对象,超级(自我,自我)

Python 未绑定的超级对象,超级(自我,自我),python,python-3.x,super,Python,Python 3.x,Super,我想问一下 sup = super(self, self) David Beazley&Brian K.Jones的Python Cookbook 3rd有很多这样的例子。这是一本书中的代码缩写: class MatchSignaturesMeta(type): def __init__(self, clsname, bases, clsdict): super().__init__(clsname, bases, clsdict) sup = supe

我想问一下

sup = super(self, self)
David Beazley&Brian K.Jones的Python Cookbook 3rd有很多这样的例子。这是一本书中的代码缩写:

class MatchSignaturesMeta(type):
    def __init__(self, clsname, bases, clsdict):
        super().__init__(clsname, bases, clsdict)
        sup = super(self, self)  
        for name, value in clsdict.items():
        # ...
            prev_dfn = getattr(sup, name, None)
        # ...

class Root(metaclass=MatchSignaturesMeta):
    pass
class A(Root):
    def foo(self, x, y):
        pass
    # ...
通过实验,我知道第二个超级参数是必须的。sup打印为:

<super: <class 'Root'>, <Root object>>

他们在文件中说

如果省略第二个参数,则返回超级对象 不受约束。”

“绑定/未绑定方法”(其第一个参数绑定到类实例的函数)是很熟悉的。 什么是“绑定对象”

在本例中,正在创建根类。我没有看到显式的根对象创建。我想问一下 根对象(来自上面的sup可打印表示)来自哪里


在Debian GNU/Linux 9.11(stretch)上使用Python 3.5.3时,Unbound super对象是一个描述符。这意味着当它作为对象属性被访问时,它具有特殊的行为

它本身没有方法定义。不过,它可以通过描述符的API创建绑定的超级对象

假设我们有以下三个类和未绑定的超级对象:

A类(对象):
def方法(自我):
返回“a”
B(A)类:
def方法(自我):
返回“b”
sup=super(B)
如果尝试从中选取方法或属性,则将失败:

sup.method
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-de4aeea2d9e8> in <module>
      1 # If you try to get any method of A, it won't work
----> 2 sup.method

AttributeError: 'super' object has no attribute 'method'
其中,
\uuuuuuThisClass\uuuuuuu
-是超级构造函数的单个参数(在我们的例子中,它是
B

因此,如果我们尝试通过实例访问属性,我们将能够访问超类的方法:

class C(B):
    sup = super(B)

# same as super(B, self).method()
C().sup.method() # -> 'a'
但请记住,您无法通过
C.sup.method
获得未绑定的超类方法。因为它相当于
super(B,None)
,后者又相当于
super(B)