如何将一个类从一个python脚本导入另一个python脚本?

如何将一个类从一个python脚本导入另一个python脚本?,python,numpy,scipy,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

我正在尝试编写一个包含一些类的脚本,并将其保存为
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)
将numpy导入为np
从scipy导入集成
类宇宙学(对象):
定义初始值(自,ωm=0.3,ωlam=0.7):
#在这个宇宙中没有精华,没有辐射!
self.omega_m=omega_m
self.omega_lam=omega_lam
self.omega_c=(1.-omega_m-omega_lam)
#self.omega_r=0
def a(自身,z):
返回1./(1+z)
def E(自我,a):
返回值(self.omega_m*a**(-3)+self.omega_c*a**(-2)+self.omega_lam)**0.5
定义内核(self,x):
返回self.E(x**-1)**-1
def Da(自,z,z_ref=0):
如果存在(z,np.N阵列):
da=np.类零(z)
对于范围内的i(len(da)):
da[i]=self.da(z[i],z_-ref)
返回da
其他:
如果z<0:
提升值错误(“z为负”)
如果z0.01):
如果self.omega_c>0:
d=信元(rk*d)/rk
如果self.omega_c<0:
d=sin(rk*d)/rk
返回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)
>>从模型导入宇宙学作为cosmo
>>>打印cosmo.a(1)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:必须使用Cosmology实例作为第一个参数调用未绑定的方法a()(改为使用int实例)

我不太明白问题出在哪里!!任何提示???

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

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

或者,如果希望a()成为类方法,则需要使用@classmethod decorator对其进行修饰,以了解更多详细信息。

@classmethod
放在
定义a
的顶部。(我假设您在方法内部根本不需要self)您的问题不是导入的
;您正在尝试调用该类上的实例方法。