[Tutor] Importing from classes or functions

Daniel Ehrenberg littledanehren at yahoo.com
Thu Oct 30 15:50:41 EST 2003


I'm trying to write a module to make it so that you
can use Ruby-style methods on various types in Python
(similar to the methods on strings, but in Ruby,
*every* method that would be builtin or in the
standard library is callable from that variable). I'm
starting with an integer where, if you call the sin()
function, it returns the sine of the number. I called
this class (for right now) sinnum. So sinnum(5).sin()
should return -0.95892427466313845. I was able to
impliment it, but I had do import math outside of the
class. I wanted to import it within the class, since
when I'm finished, the module should contain more than
one datatype (an extended int, an extended float, an
extended string, etc). But when I try to impliment
importing within the class, the import doesn't work.

>>> class sinnum(int):
...     def __init__(s, number):
...         import math
...         s.num = number
...     def sin(s):
...         return math.sin(s)
...     
>>> x = sinnum(5)
>>> x.sin()
Traceback (most recent call last):
  File "<input>", line 1, in ?
  File "<input>", line 6, in sin
NameError: global name 'math' is not defined

I was able to simplify my error to this, if it helps:

>>> def importmath():
...     import math
...     
>>> importmath()
>>> math.sin(5)
Traceback (most recent call last):
  File "<input>", line 1, in ?
NameError: name 'math' is not defined

If Ruby-style methods for Python is a bad idea or
would be extremely inefficient, please tell me.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/



More information about the Tutor mailing list