我怎么能从python脚本导入一个类到另一个python脚本?

时间:2014-05-25 21:16:31

标签: python numpy scipy

我正在尝试编写包含一些类的脚本,并保存为model.py

import numpy as np
from scipy import integrate

class Cosmology(object):
    def __init__(self, omega_m=0.3, omega_lam=0.7):
        # no quintessence, no radiation in this universe!
        self.omega_m = omega_m
        self.omega_lam = omega_lam
        self.omega_c = (1. - omega_m - omega_lam)
        #self.omega_r = 0

    def a(self, z):
        return 1./(1+z)

    def E(self, a):
        return (self.omega_m*a**(-3) + self.omega_c*a**(-2) + self.omega_lam)**0.5

    def __angKernel(self, x):
        return self.E(x**-1)**-1

    def Da(self, z, z_ref=0):
        if isinstance(z, np.ndarray):
            da = np.zeros_like(z)
            for i in range(len(da)):
                da[i] = self.Da(z[i], z_ref)
            return da
        else:
            if z < 0:
                raise ValueError(" z is negative")
            if z < z_ref:
                raise ValueError(" z should not not be smaller than the reference redshift")

            d = integrate.quad(self.__angKernel, z_ref+1, z+1,epsrel=1.e-6, epsabs=1.e-12)
            rk = (abs(self.omega_c))**0.5
            if (rk*d > 0.01):
                if self.omega_c > 0:
                    d = sinh(rk*d)/rk
                if self.omega_c < 0:
                    d = sin(rk*d)/rk
            return d/(1+z)

然后我想将Cosmology类调用到另一个脚本中,但是我收到以下错误:

>>>from model import Cosmology as cosmo
>>>print cosmo.a(1.)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method a() must be called with Cosmology instance as first argument (got int instance instead)

我不太明白问题是什么!任何提示??

1 个答案:

答案 0 :(得分:2)

您正在尝试从类中调用实例方法。要使用a()方法,您需要创建Cosmology类的实例:

>>>from model import Cosmology
>>>cosmo = Cosmology()
>>>cosmo.a(1.)
0.5

或者,如果你想让a()成为一个类方法,你需要用@classmethod装饰器 - see here来装饰它,以获取更多细节。

相关问题