首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >父类python中超级关键字的含义

父类python中超级关键字的含义
EN

Stack Overflow用户
提问于 2015-06-15 15:42:50
回答 2查看 710关注 0票数 1

当超级关键字不在子类中使用时,我不理解它的含义。

这个问题来自这里的这个类,我在我正在工作的一个git集线器项目中找到了这个类(链接是https://github.com/statsmodels/statsmodels/pull/2374/files)。

例如,查看出现代码fitres = super(PenalizedMixin, self).fit(method=method, **kwds) +方法。

代码语言:javascript
复制
"""
+Created on Sun May 10 08:23:48 2015
+
+Author: Josef Perktold
+License: BSD-3
+"""
+
+import numpy as np
+from ._penalties import SCADSmoothed
+
+class PenalizedMixin(object):
+    """Mixin class for Maximum Penalized Likelihood
+
+
+    TODO: missing **kwds or explicit keywords
+
+    TODO: do we really need `pen_weight` keyword in likelihood methods?
+
+    """
+
+    def __init__(self, *args, **kwds):
+        super(PenalizedMixin, self).__init__(*args, **kwds)
+
+        penal = kwds.pop('penal', None)
+        # I keep the following instead of adding default in pop for future changes
+        if penal is None:
+            # TODO: switch to unpenalized by default
+            self.penal = SCADSmoothed(0.1, c0=0.0001)
+        else:
+            self.penal = penal
+
+        # TODO: define pen_weight as average pen_weight? i.e. per observation
+        # I would have prefered len(self.endog) * kwds.get('pen_weight', 1)
+        # or use pen_weight_factor in signature
+        self.pen_weight =  kwds.get('pen_weight', len(self.endog))
+
+        self._init_keys.extend(['penal', 'pen_weight'])
+
+
+
+    def loglike(self, params, pen_weight=None):
+        if pen_weight is None:
+            pen_weight = self.pen_weight
+
+        llf = super(PenalizedMixin, self).loglike(params)
+        if pen_weight != 0:
+            llf -= pen_weight * self.penal.func(params)
+
+        return llf
+
+
+    def loglikeobs(self, params, pen_weight=None):
+        if pen_weight is None:
+            pen_weight = self.pen_weight
+
+        llf = super(PenalizedMixin, self).loglikeobs(params)
+        nobs_llf = float(llf.shape[0])
+
+        if pen_weight != 0:
+            llf -= pen_weight / nobs_llf * self.penal.func(params)
+
+        return llf
+
+
+    def score(self, params, pen_weight=None):
+        if pen_weight is None:
+            pen_weight = self.pen_weight
+
+        sc = super(PenalizedMixin, self).score(params)
+        if pen_weight != 0:
+            sc -= pen_weight * self.penal.grad(params)
+
+        return sc
+
+
+    def scoreobs(self, params, pen_weight=None):
+        if pen_weight is None:
+            pen_weight = self.pen_weight
+
+        sc = super(PenalizedMixin, self).scoreobs(params)
+        nobs_sc = float(sc.shape[0])
+        if pen_weight != 0:
+            sc -= pen_weight / nobs_sc  * self.penal.grad(params)
+
+        return sc
+
+
+    def hessian_(self, params, pen_weight=None):
+        if pen_weight is None:
+            pen_weight = self.pen_weight
+            loglike = self.loglike
+        else:
+            loglike = lambda p: self.loglike(p, pen_weight=pen_weight)
+
+        from statsmodels.tools.numdiff import approx_hess
+        return approx_hess(params, loglike)
+
+
+    def hessian(self, params, pen_weight=None):
+        if pen_weight is None:
+            pen_weight = self.pen_weight
+
+        hess = super(PenalizedMixin, self).hessian(params)
+        if pen_weight != 0:
+            h = self.penal.deriv2(params)
+            if h.ndim == 1:
+                hess -= np.diag(pen_weight * h)
+            else:
+                hess -= pen_weight * h
+
+        return hess
+
+
+    def fit(self, method=None, trim=None, **kwds):
+        # If method is None, then we choose a default method ourselves
+
+        # TODO: temporary hack, need extra fit kwds
+        # we need to rule out fit methods in a model that will not work with
+        # penalization
+        if hasattr(self, 'family'):  # assume this identifies GLM
+            kwds.update({'max_start_irls' : 0})
+
+        # currently we use `bfgs` by default
+        if method is None:
+            method = 'bfgs'
+
+        if trim is None:
+            trim = False  # see below infinite recursion in `fit_constrained
+
+        res = super(PenalizedMixin, self).fit(method=method, **kwds)
+
+        if trim is False:
+            # note boolean check for "is False" not evaluates to False
+            return res
+        else:
+            # TODO: make it penal function dependent
+            # temporary standin, only works for Poisson and GLM,
+            # and is computationally inefficient
+            drop_index = np.nonzero(np.abs(res.params) < 1e-4) [0]
+            keep_index = np.nonzero(np.abs(res.params) > 1e-4) [0]
+            rmat = np.eye(len(res.params))[drop_index]
+
+            # calling fit_constrained raise
+            # "RuntimeError: maximum recursion depth exceeded in __instancecheck__"
+            # fit_constrained is calling fit, recursive endless loop
+            if drop_index.any():
+                # todo : trim kwyword doesn't work, why not?
+                #res_aux = self.fit_constrained(rmat, trim=False)
+                res_aux = self._fit_zeros(keep_index, **kwds)
+                return res_aux
+            else:
+                return res
+
+

我尝试用一个更简单的例子来重现这段代码,但它不起作用:

代码语言:javascript
复制
class A(object):
    def __init__(self):
        return

    def funz(self, x):
        print(x)

    def funz2(self, x):
        llf = super(A, self).funz2(x)
        print(x + 1)

a = A()
a.funz(3)
a.funz2(4)


Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/donbeo/Desktop/prova.py", line 15, in <module>
    a.funz2(4)
  File "/home/donbeo/Desktop/prova.py", line 10, in funz2
    llf = super(A, self).funz2(x)
AttributeError: 'super' object has no attribute 'funz2'
>>> 
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-15 15:57:36

您应该始终使用super,因为否则类可能会被遗漏,特别是在多继承场景中的,尤其是(在使用混合类的地方,这是不可避免的)。例如:

代码语言:javascript
复制
class BaseClass(object):

    def __init__(self):
        print 'BaseClass.__init__'


class MixInClass(object):

    def __init__(self):
        print 'MixInClass.__init__'


class ChildClass(BaseClass, MixInClass):

    def __init__(self):
        print 'ChildClass.__init__'
        super(ChildClass, self).__init__()  # -> BaseClass.__init__


if __name__ == '__main__':
    child = ChildClass()

给予:

代码语言:javascript
复制
ChildClass.__init__
BaseClass.__init__

MixInClass.__init__遗漏了,而:

代码语言:javascript
复制
class BaseClass(object):

    def __init__(self):
        print 'BaseClass.__init__'
        super(BaseClass, self).__init__()  # -> MixInClass.__init__


class MixInClass(object):

    def __init__(self):
        print 'MixInClass.__init__'
        super(MixInClass, self).__init__()  # -> object.__init__


class ChildClass(BaseClass, MixInClass):

    def __init__(self):
        print 'ChildClass.__init__'
        super(ChildClass, self).__init__()  # -> BaseClass.__init__


if __name__ == '__main__':
    child = ChildClass()

给予:

代码语言:javascript
复制
ChildClass.__init__
BaseClass.__init__
MixInClass.__init__

ChildClass.__mro__,“方法解析顺序”,在这两种情况下都是相同的:

代码语言:javascript
复制
(<class '__main__.ChildClass'>, <class '__main__.BaseClass'>, <class '__main__.MixInClass'>, <type 'object'>)

BaseClassMixInClass都只继承object (即它们是“新样式”类),但是仍然需要使用super来确保调用MRO中类中的任何其他实现。要启用这种使用,object.__init__是实现的,但实际上并不是很多!

票数 4
EN

Stack Overflow用户

发布于 2015-06-15 15:46:00

PenalizedMixin是一个子类:它是object的一个子类。

然而,顾名思义,它意味着是一个混合体。也就是说,它打算用作多继承场景中的父级。super按方法解析顺序调用下一个类,该类不一定是该类的父类。

无论如何,我不明白你“简单”的例子。原始代码工作的原因是超类确实有一个__init__方法。object没有funz2方法。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30849383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档