I'm working on writing my first Python class. Being the java programmer that I am, I have something like this:
#class1.py
class class1:
def __init__(self):
#Do stuff here
And in my current script:
import class1
object = class1()
I'm getting a Name Error: name 'class1' is not defined
I've also tried this, with no luck:
import class1
object = class1.class1()
The error I get here is AttributeError: 'module' object has no attribute 'class1'
What am I doing wrong?
Python import is by module and then by the contents of the module, so for your class1.py it becomes:
from class1 import class1
Python module docs
In Python you import the modules. For class1.py file you can use:
from class1 import class1
Or if you have more than one....
from class1 import *
Related
I have this error:
My project structure is:
All __init__.py are empty
main.py
from testclass import class1
from testclass import class2
l1 = class1()
l2 = class2()
class1.py
class class1():
def __init__(self):
print('hello')
if __name__ == '__main__':
ldummy = class1()`
class2.py
import class1
class class2(class1.class1):
def __init__(self):
class1.class1.__init__(self)
print('hola')
if __name__ == '__main__':
ldummy = class2()
I don't see what's not good about that
If you read your error message carefully, you will see that the actual error occurs when class2 tries to import class1 which it cannot. The reason for that is that the reference remains the level where main is located even for class2. So you need this content in class2:
from testclass import class1 # Instead of import class1
class class2(class1.class1):
def __init__(self):
class1.class1.__init__(self)
print('hola')
if __name__ == '__main__':
ldummy = class2()
EDIT:
Answering your comment:
There are a few ways to achieve the desired behaviour, but I wouldn't necessarily say that they are pythonic. Before importing, you can add the main folder to the python path in class2.py
import sys
def import():
sys.path.append(main_path)
Alternatively you could also add the path permanently to the python path.
A third option is to use a try-except-clause around your import:
try:
from testclass import class1
except ModuleNotFoundError:
import class1
I would argue that none of these options are great and could eventually cause errors. Better to have clear and unique ways of calling your functions.
I'm new to python and I'm trying to create a module and class.
If I try to import mystuff and then use cfcpiano = mystuff.Piano(), I get an error:
AttributeError: module 'mystuff' has no attribute 'Piano'
If I try from mystuff import Piano I get:
ImportError: cannot import name 'Piano'
Can someone explain what is going on? How do I use a module and class in Python
mystuff.py
def printhello():
print ("hello")
def timesfour(input):
print (input * 4)
class Piano:
def __init__(self):
self.type = raw_input("What type of piano? ")
def printdetails(self):
print (self.type, "piano, " + self.age)
Test.py
import mystuff
from mystuff import Piano
cfcpiano = mystuff.Piano()
cfcpiano.printdetails()
If you want to create a python module named mystuff
Create a folder with name mystuff
Create an __init__.py file
#__init__.py
from mystuff import Piano #import the class from file mystuff
from mystuff import timesfour,printhello #Import the methods
Copy your class mystuff.py to the folder mystuff
Create file test.py outside the folder(module) mystuff.
#test.py
from mystuff import Piano
cfcpiano = Piano()
cfcpiano.printdetails()
I am encountering a problem using a circular importation in Python 2.7
For some reasons, I need this structure, here reduced for the explanation to 4 python files :
- main.py
- folder
\- __init__.py
\- loader.py
\- folder1
\- __init__.py
\- class1.py
\- folder2
\- __init__.py
\- class2.py
main.py :
import folder.loader as LD
LD.a.change_class2()
LD.b.change_class1()
loader.py :
from folder1.class1 import Class1
from folder2.class2 import Class2
a=Class1()
b=Class2()
class1.py :
import folder.loader as LD
class Class1():
def __init__(self):
self.pty1=0
def change_class2(self):
LD.b.pty2=2
class2.py :
import folder.loader as LD
class Class2():
def __init__(self):
self.pty2=0
def change_class1(self):
LD.a.pty1=6
The code executed is main.py. This script calls the file loader.py which creates an instance for Class1 and Class2. The instances have to communicate and modify each other, explaining the necessity (if I am not wrong) of the file loader.py.
Executing this code returns the error from class1.py :
import folder.loader as LD
AttributeError: 'module' object has no attribute 'loader'
I have no idea of what is going on here.
Surprisingly, when I remove the part as LD from the importation command line in the classes files, it works perfecly :
class1.py :
import folder.loader
class Class1():
def __init__(self):
self.pty1=0
def change_class2(self):
folder.loader.b.pty2=2
class2.py :
import folder.loader
class Class2():
def __init__(self):
self.pty2=0
def change_class1(self):
folder.loader.a.pty1=6
For this example, it's ok, but in the real program I am trying to make, based on this structure, I can't use the complete module path each time I need to communicate with another class instance.
Why am I getting this error ? What can I do to solve this ?
Thank you in advance for your help.
EDIT : replacing import folder.loader as LD by from .. import loader as LD now returns another error, that I don't understand :
from .. import loader as LD
ImportError: cannot import name loader
I solved the problem simply by using Python 3, without code changes.
I have a module module.py
class SomeClass():
def __init__(self):
self.var='123'
def printit(self):
print self.var
And now I'm trying to import this module into script.py and call the method printit from the class SomeClass
import module
module.SomeClass().printit()
I also can do it by another way:
from module import SomeClass
SomeClass().printit()
And another one:
from module import SomeClass as module
module().printit()
It's nice but i want to get something like this:
import module
module().printit()
or even
import module
SomeClass().printit()
Generally I want to make a module that will export SomeClass by default. Is it possible to make something like this by changing module.py?
I've continually looked up solutions to this and I can't find a simple answer. I'm trying to create an object from an imported class, and then call a method on that object.
from MySchedule import *
my_schedule = MySchedule(self.driver)
my_schedule.navigate_to_my_schedule() # getting an error here
Error is
AttributeError: MySchedule object has no attribute 'navigate_to_my_schedule'
Code from MySchedule.py:
class MySchedule:
def __init__(self, driver):
self.driver = driver
self.nav_btn = self.driver.find_element_by_id('locButton_1')
self.header = self.driver.find_element_by_id('panelTitle_1')
def navigate_to_my_schedule(self):
self.nav_btn.click()
The problem is that you're using MySchedule as both the module name and the class name, and are using from MySchedule import *.
I'd recommend changing the import statement to
import MySchedule
and referring to the class as MySchedule.MySchedule.
For further discussion of wildcard imports, see Should wildcard import be avoided?