2014-05-25 3 views
0

일부 클래스가 들어있는 스크립트를 작성하려고하는데 예를 들어 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) 

는 그럼 난 다른 스크립트로 우주론 클래스를 호출 할, 그러나 나는 다음과 같은 오류 얻을 :

>>>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) 

내가 확실히 문제가 무엇인지 이해하지를! 모든 팁 ??

+0

'def a'의 맨 위에'@ classmethod'를 넣으십시오. (나는 당신이 방법의 내부에서 자아를 필요로하지 않는다고 가정한다) –

+1

당신의 문제는'import'가 아니다; 클래스에 * 인스턴스 메서드 *를 호출하려고합니다. – jonrsharpe

답변

2

클래스에서 인스턴스 메서드를 호출하려고합니다. 당신이 원하는 경우() 클래스 메소드로, 당신은 그것을 장식 할 필요가

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

또는 @으로 a() 메소드를 사용하려면, 당신은 우주론 클래스의 인스턴스를 생성해야 classmethod 데코레이터 - see here 자세한 내용은

관련 문제