Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating a Class in Interactive Python Shell

in a .py file I have the following:

class avgbox:
    def __init__(self,t,n,a):
        self.t = t
        self.n = n
        self.a = a
    def add(x):
        self.t += x
        self.n += 1
        self.a = t/n

Now when I do the from file.py import * in the interactive python shell run from the ubuntu command line, it shows no error. Then when do a = avgbox(0,0,0) it says NameError: name 'avgbox' is not defined. Any ideas? What am I doing wrong here? Thanks!

like image 310
BrownBeard93423 Avatar asked Sep 14 '26 10:09

BrownBeard93423


1 Answers

I copy pasted your code into a file named "file.py". Then I did the following:

from file import *

avgbox(1, 2, 3)

It worked. Maybe your mistake was that you were doing from file.py import * when you should just be doing from file import * Remember that when Python searches for module names, it automatically appends .py to the name of the module if it's looking for a Python file within the current directory. Of course, you can also search within packages using the from syntax, but that's a different story.

like image 152
Shashank Avatar answered Sep 16 '26 00:09

Shashank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!