Scipy.Stats.exponweib的子类不调用__init__或其他函数

时间:2017-01-11 20:56:08

标签: python class scipy

我正在尝试创建一个子类来简化scipy.stats.exponweib包的输入以及添加一些额外的功能。简化了类在自己的文件中调用weibull.py

from scipy.stats import exponweib
# import scipy

class weibull(exponweib):

    def __init__(self,beta,nu):
        super(weibull,self).__init__(a=1,c=beta,loc=0,scale=nu)
        print beta
        print nu

    def doSomething(self,s):
        print(s)

我的测试脚本类似于:

from weibull import weibull

w = weibull(2.6,2600)
print('%0.10f'%w.pdf(1000))
w.doSomething('Something')

似乎我的__init__根本没有运行,所有打印语句都没有运行,并且在doSomething例程中抛出了错误。

终端输出如下:

Codes> python weibull_testHarness.py
0.0000000000
Traceback (most recent call last):
  File "weibull_testHarness.py", line 5, in <module>
    w.doSomething('Something')
AttributeError: 'rv_frozen' object has no attribute 'doSomething'

1 个答案:

答案 0 :(得分:2)

Per NumPy / SciPy开发人员Robert Kern's answer,子类rv_frozen,而不是exponweib

请注意exponweibinstance of the class exponweib_gen

In [110]: stats.exponweib
Out[110]: <scipy.stats._continuous_distns.exponweib_gen at 0x7fd799db2588>

exponweib is itself a callable,返回rv_frozen的实例。

In [107]: exponweib(a=1, c=2.6)
Out[107]: <scipy.stats._distn_infrastructure.rv_frozen at 0x7fd7997282b0>

因此,按照这种模式,w = weibull(2.6, 2600)将是rv_frozen的一个实例。如果您希望w拥有其他方法,那么您需要继承rv_frozen,而不是exponweib,也不需要exponweib_gen,也不需要rv_continuous。< / p>

import scipy.stats as stats

class my_frozen(stats._distn_infrastructure.rv_frozen):

    def __init__(self, dist, *args, **kwds):
        super(my_frozen,self).__init__(dist, *args, **kwds)
        print(kwds)

    def doSomething(self,s):
        print(s)

def weibull(beta, nu):
    dist = stats.exponweib # an instance of stats._continuous_distns.exponweib_gen
    dist.name = 'weibull'
    return my_frozen(dist, a=1, c=beta, loc=0, scale=nu)

w = weibull(2.6, 2600)
print('%0.10f'%w.pdf(1000))
w.doSomething('Something')

产量

{'loc': 0, 'scale': 2600, 'c': 2.6, 'a': 1}
0.0001994484
Something