0

I have a python file named Point2.py, which has the following code

class Point():   
    def __init__(self,x=0,y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return "%d,%d" %(self.x,self.y)

Now in the interpreter, I did this:

>>> import Point2
>>> p1 = Point()

But I received an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable

The Point2.py file has Point class in it. Why I am not able to assign it to p1. When I tried:

>>> from Point import *

>>> p1 = Point() 

It works

I renamed the file to Point.py and then I did

>>> import Point
>>> p1 = Point 

and this works, but assigning values are not easy.

However,

>>> from Point import *
>>> p1 = Point(3,4)  

works.

My question is why it behaves differently when I import Point and when I did from Point import *. Which way of importing is a good style?

And is there any relevance for class and the filename?

TerryA
  • 58,805
  • 11
  • 114
  • 143
brain storm
  • 30,124
  • 69
  • 225
  • 393

1 Answers1

4

To answer why:

>>> import Point2
>>> p1 = Point()

doesn't work, is because you did not directly import the class Point(). To access the Point() class, you'll want to do:

>>> import Point2
>>> p1 = Point2.Point()

Or

>>> from Point2 import Point
>>> p1 = Point()

Doing from x import * imports everything from the module. So if there was a function foo() in a module bar, doing from bar import foo would import the function so you could do foo() and not have to do bar.foo(). This is why when you did from Point import *, it worked as you didn't need to do Point.Point().


Which way is better to import? Well, doing from x import * isn't recommended unless you're going to use everything in x. It can also get mixed up with functions in your own script.

With from x import y or import x, take a look at this question.

Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • Thanks, I got it clear now. One other offshoot question I have is – brain storm Mar 17 '13 at 05:35
  • Thanks, I got it clear now. One other offshoot question I have is what difference I have if I define a method in my Point class as def add(self,other) and def __add__(self,other). i.e, what is the differnce here, def __add__(self,other): return "%d,%d" %(self.x+other.x,self.y+other.y) def addtwo(self,other): return "%d,%d" %(self.x+other.x,self.y+other.y) and how to use them would be very helpful – brain storm Mar 17 '13 at 05:46
  • I don't believe there is a difference (I myself aren't very experienced with classes) but to use them, you would do `a = Point()` `a.__add__(x)` where x is/are your parameter/s. – TerryA Mar 17 '13 at 06:23
  • In your case you should be returning numbers, instead of strings for your add. `def __add__(self,other): return (self.x+other+x, self.y+other.y)` Actually maybe you should be returning a new Point() with the new values. That i'm not sure. – ninMonkey Mar 17 '13 at 17:09