[Tutor] Importing from classes or functions

Gregor Lingl glingl at aon.at
Thu Oct 30 16:25:32 EST 2003



Daniel Ehrenberg schrieb:

>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. 
>
You can import a module into an arbitrary namspace with the
buit in function __import__

for instance:

 >>> class C:
    m = __import__("math")    # class-attribute
    def test(self):
        print C.m.sin(C.m.pi/2)

       
 >>> c = C()
 >>> c.test()
1.0

or, as you wanted:

 >>> class sinnum:
    def __init__(self, number):
        self.m = __import__("math")  # instance - attribute
        self.num = number
    def sin(self):
        return self.m.sin(self.num)

   
 >>> x = sinnum(5)
 >>> x.sin()
-0.95892427466313845
 >>>

HTH, Gregor


>  
>




More information about the Tutor mailing list