I can't instantiate a simple class in Python
I want to generate a Python class via a file. This is a very simple file, named testy.py:
def __init__(self,var):
print (var)
When I try to instantiate it I get:
>>> import testy
>>> testy('1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
Then , I try something else:
class testy_rev1:
def __init__(self,var):
print (var)
I try to instanicate it and I get:
>>> import testy_rev1
>>> a=testy_rev1('1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> a=testy_rev1.testy_r开发者_Python百科ev1('1')
1
What I am looking for is a way to import it from a file w/o resorting to:
import <module name>.<module name>
With a file called testy.py with this:
class testy_rev1:
def __init__(self, var):
print (var)
You will have to do either:
>>> import testy
>>> testy.testy_rev1('1')
Or:
>>> from testy import testy_rev1
>>> testy_rev1('1')
Or (not recommended, since you will not see where the definition came from in the source):
>>> from testy import *
>>> testy_rev1('1')
Other than that I do not know how you could do it.
Attempt 1 failed because you were not defining a class, just a function (which you fixed with attempt 2).
Attempt 2 is failing because you looking at the import
statement like it is a Java import
statement. In Python, an import
makes a module object that can be used to access items inside it. If you want use a class with in a module without first specifying the module you want to use the following:
from my_module import MyClass
a = MyClass()
As a side note, your print method in the 2nd attempt in not indented after the __init__
method. This might just me a formatting error when you posted here, but it will not run the code how you expect.
import x
imports a module called x
. import y.x
imports the module d
from the module/package y
. Anything in this module is refered to as x.stuff
or y.x.stuff
. That's how it works and they won't change the language for your convenience ;)
You can always do from module import thingy
. But consider that importing the whole module is usually preferred over this... for a reason (to make clearer where it came from, to avoid namespace clashes, because "explicit is better than mplicit")!
精彩评论