我试图创建一个子类,以简化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'

最佳答案

每个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而不是exponweibexponweib_genrv_continuous子类化。



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

09-04 16:19