Python类和函数的NoneType错误

时间:2015-05-08 16:14:53

标签: python class nonetype object-oriented-analysis

尽管我的函数返回一个数组,但我收到TypeError: 'NoneType' object is not callable错误。我首先定义类,然后插入函数。 我对Python比较陌生,并且非常感谢任何帮助/评论。

课程是:

from scipy import array, dot, zeros, empty
from scipy.optimize import brentq
from numpy import *
from numpy.random import uniform 
from time import time

# from mpi4py import MPI

class UtilTheory:
    """

    """

    def utility(self, other):
        raise NotImplementedError("You need to implement method 'utility' "
                                  "in the child class.")

    def demand(self, p):
        raise NotImplementedError("You need to implement method 'demand' "
                                  "in the child class.")


    def excessDemand(self, p):
        p = array(p)
        return self.demand(p) - self.endowment

    def indUtility(self, p):
        x = self.demand(p)
        return self.utility(x)

    def __add__(self, other):
        economy = Economy([self, other])

        return economy

    def __radd__(self, other):
        economy = Economy([self] + other)

    def __rmul__(self, other):
        economy = Economy(other * [self])

        return economy

class Consumer(UtilTheory, object):
    """
    Defines general features of a consumer
    """

    def __init__(self, endowment=array([1,1]), alpha=0.5, rho=0.0):
        self.endowment = array(endowment)
        self.alpha = float(alpha)
        self.rho = rho
        self.sigma = 1.0 / (1.0 - rho)

    def __str__(self):
        return ('e=' + str(self.endowment) +
                ', alpha=' + str(self.alpha) +
                ', rho=' + str(self.rho))

    def demand(self, p):
        endowment = self.endowment
        alpha = self.alpha
        sigma = self.sigma
        p = array(p)
        m = dot(endowment, p)

        x1 = ((alpha / p[0]) ** sigma * m /
              (alpha ** sigma * p[0] ** (1 - sigma) +
              (1 - alpha) ** sigma * p[1] ** (1 - sigma)))

        x2 = (((1.0 - alpha) / p[1]) ** sigma * m /
              (alpha ** sigma * p[0] ** (1 - sigma) +
              (1 - alpha) ** sigma * p[1] ** (1 - sigma)))

        return array([x1, x2])

    def utility(self, x):
        if self.rho != 0:
            return ((self.alpha * x[0] ** self.rho +
                    (1.0 - self.alpha) * x[1] ** self.rho) **
                       (1.0 / self.rho))

        return x[0] ** self.alpha * x[1] ** (1.0 - self.alpha)

class Economy:
    """
    Consists of consumers
    """

    def __init__(self, consumers):
        """
        Consumers should be a list of consumers
        """

        self.consumers = consumers

    def excessDemand(self, p):
        result = zeros(2)
        for consumer in self.consumers:
            result = result + consumer.excessDemand(p)

        return result

    def demand(self, p):
        result = zeros(2)
        for consumer in self.consumers:
            result = result + consumer.demand(p)

        return result

    def excessDemandGood0(self, p0):
        p = array([p0, 1.0 - p0])
        result = 0

        for consumer in self.consumers:
            result = result + consumer.excessDemand(p)[0]

        return result

    def __add__(self,other):
        try:
            return Economy(self.consumers + other.consumers)
        except:
            return Economy(self.consumers + [other])

    def numEquilibria(self, n=100):
        # p = array([p0, 1 - p0])
        q = linspace(0, 1, n)
        result = empty(len(q))
        #print result
        for i, p0 in enumerate(q):
            a = self.excessDemandGood0(p0)
            #print a
            result[i] = a
        index = zeros(len(q))

        for i in range(1, 2):
            if result[i] <= 0:  
                index[i - 1] = 1
            else: 
                index[i - 1] = 0

        for i in range(2, n - 1):
            test=result[i - 1] * result[i]
            #print test
            if test <= 0:
                index[i - 1] = 1
            else:
                index[i - 1] = 0

        for i in range(n - 2, n - 1):
            if result[i] > 0:
                index[i - 1] = 1
            else:
                index[i - 1] = 0

        count = sum(index)
        # print "The number of equilibria is"
        return count
        # print "Excess Demand funciton on the grid:"
        # print result
        # print "Index when excess demand goes from possitive to negative"
        # print index

    def __rmul__(self, other):
        economy = Economy(other * self.consumers)

        return economy

    def equilibrium(self, startbracket=None):
        def g(x):
            return self.excessDemandGood0(x)

        if startbracket == None:
            startbracket = [1e-10, 1-1e-10]

        eqPrice1 = brentq(g, startbracket[0], startbracket[1])

        return array([eqPrice1, 1 - eqPrice1])

    def __len__(self):
        return len(self.consumers)

    def __str__(self):
        resultString = 'Economy with ' + str(len(self)) + ' consumers.\n'

        for consumer in self.consumers:
            resultString = resultString + str(consumer) + '\n'

        return resultString

我在实现调用stats()的{​​{1}}函数时遇到错误:

randomEconEq()

在实现函数def randomEcon(e1=[1, 0], e2=[0, 1], iterate_max=100): rho1 = random.uniform(-8, -1) rho2 = random.uniform(-8, -1) alpha1 = random.uniform(0, 1) alpha2 = random.uniform(0, 1) x = Consumer(endowment=e1, alpha=alpha1, rho=rho1) y = Consumer(endowment=e2, alpha=alpha2, rho=rho2) econ = Economy([x, y]) return econ def randomEconEq(iterate_max=100): iterate = 0 eq_vec = [] start = time() while iterate < iterate_max: iterate += 1 econ = randomEcon() equilibria = econ.numEquilibria() eq_vec.append(equilibria) # print eq_vec if (econ.numEquilibria() > 1): print "Number of multiple equilibria is " + \ str(econ.numEquilibria()) print str(econ) print str(eq_vec) end = time() totaltime = end - start #print('Total Time is ' + str(totaltime)) return eq_vec def stats(eq_vec, iterate_max): one_eq = zeros(len(eq_vec)) three_eq = zeros(len(eq_vec)) five_eq = zeros(len(eq_vec)) more_eq = zeros(len(eq_vec)) # print (eq_vec) for i in range(len(eq_vec)): if eq_vec[i] == 1: one_eq[i] = 1 if eq_vec[i] == 3: three_eq[i] = 1 if eq_vec[i] == 5: five_eq[i] = 1 if eq_vec[i] > 5: more_eq[i] = 1 Eq1 = sum(one_eq) Eq3 = sum(three_eq) Eq5 = sum(five_eq) EqMore = sum(more_eq) prob1 = float((Eq1 / iterate_max) * 100) prob3 = float((Eq3 / iterate_max) * 100) prob5 = float((Eq5 / iterate_max) * 100) probMore = float((EqMore/iterate_max) * 100) print ('The Vector of the number of equililbria is:' + str(eq_vec)) print ('Probability of 1 equilibrium is (percent) ' + str(prob1)) print ('Probability of 3 equilibria is (percent) ' + str(prob3)) print ('Probability of 5 equilibria is (percent) ' + str(prob5)) print ('Probability of 1 equilibria is (percent) ' + str(probMore)) eq_vec = randomEconEq(100) stats(eq_vec, 100) 时,错误出现在最后两行代码中。

创建错误的示例是:

stats()

完整的追溯是:

stats(randomEconEq(100), 100)

0 个答案:

没有答案