0

I am trying to write a script contains some classes and save for example as 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)

Then I want to call Cosmology class into another script, but I get the following error:

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

I don't quite understand what the problem is!! Any tips??

2
  • put @classmethod on top of the def a. (I assume you don't need self at all inside of the method) Commented May 25, 2014 at 21:20
  • 1
    Your problem isn't the import; you're trying to call an instance method on the class. Commented May 25, 2014 at 21:20

1 Answer 1

2

You are trying to call an instance method from a class. In order to use the a() method, you need to create an instance of the Cosmology class:

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

Or, if you want a() to be a class method, you need to decorate it with the @classmethod decorator - see here for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.