Python class definition--import statement - python

I have defined 2 classes- Person & Manager. The Manager inherits the Person class.
I get a error while trying to import the Person class..
Code is give below.
Person.py
class Person:
def __init__(self, name, age, pay=0, job=None):
self.name = name
self.age = age
self.pay = pay
self.job = job
def lastname(self):
return self.name.split()[-1]
def giveraise(self,percent):
#return self.pay *= (1.0 + percent)
self.pay *= (1.0 + percent)
return self.pay
Manager.py
from Basics import Person
class Manager(Person):
def giveRaise(self, percent, bonus=0.1):
self.pay *= (1.0 + percent + bonus)
return self.pay
Error statements:
C:\Python27\Basics>Person.py
C:\Python27\Basics>Manager.py
Traceback (most recent call last):
File "C:\Python27\Basics\Manager.py", line 1, in
from Basics import Person
ImportError: No module named Basics
Why do I get the No module found error?

You should look up how import and PYTHONPATH work. In your case, you can solve that using:
from Person import Person
I see you're coming from a Java background (where each file must have a class with the same name of the file), but that's not how Python modules work.
In short, when you run a Python script from the command line, as you did, it looks for modules (among other places) in your current dir. When you import a (simple) name like you did, Python will look for:
A file named Basic.py; or:
A folder named Basic with a file named __init__.py.
Then it will look for a definition inside that module named Person.

Because it's in Person.py, not Basics.py.
from Person import Person

You defined the Person class in a file named Person.py. Therefore, you should import it like this:
from Person import Person
Note that it's the convention in Python to have lowercase module names. For example, rename Person.py to person.py and Manager.py to manager.py. Then you'd import the Person class like this:
from person import Person
If the person module is part of a package, you'd probably want to import like this:
from .person import Person
This will ease the transition to Python 3.

from Basics import Person should be from Person import Person. You don't have a Basics.py module to import from.

Related

Python Error Import Class another directory

I have structure project python
MyProject
+Classes
-stage_competition.py
main.py
Executing Python (main.py) - Show error "ModuleNotFoundError("No module named 'Classes'",)"
I tried import direct, but is not working too, always showing same error
from Classes.stage_competition import Stage_competition
item = Stage_competition("field1", "field2", "field3" , "field4")
Create class Stage_competition
class Stage_competition(object):
"""description of class"""
def __init__(self, type_competition, datalake, competition ,hour):
self.type_competition = type_competition
self.datalake = datalake
self.competition = competition
self.hour = hour
def settype_competition(self, type_competition):
self.type_competition = type_competition
def setdatalake(self, datalake):
self.datalake = datalake
def getcompetition(self):
return self.competition
def gethour(self):
return self.hour
If the Classes is in the same folder as main.py, you should import it this way (notice the dot before Classes):
from .Classes.stage_competition import Stage_competition
Alternatively, you could add directory to Classes to PYTHONPATH, which allows you to import Classes from anywhere.

Can not import a class from another file in the same directory in Python

I am quite new to Python and I am still getting used to it. I have a project which was written by using a bunch of files containing only function definitions. I decided to remake it in OOP paradigm so this is what happens:
Back then, I had these two files:
Main
| ---- loggingManager.py
| ---- servoManager.py
in the servoManager.py script I had:
from loggingManager import *
...
from time import sleep
and it all works fine. I can use all of the functions defined in loggingManager.py without any issues.
Now I have it like this:
Main
| ---- Logger.py
| ---- ConfigurationWrapper.py
The content of the ConfigurationWrapper is :
import configparser
class ConfigurationWrapper:
default_path = '/home/pi/Desktop/Bree/config.ini'
def __init__(self, path_to_file=None):
if path_to_file is None:
path_to_file = self.default_path
...
and Logger looks like this:
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwarg$
else:
cls._instances[cls].__init__(*args, **kwargs)
return cls._instances[cls]
class Logger():
__metaclass__ = Singleton
My goal here is to import:
import ConfigurationWrapper
in Logger.py script file but every time I do that, I get an error (by typing 'python Logger' in the terminal on MacOS):
Traceback (most recent call last):
File "Logger", line 1, in <module>
import ConfigurationWrapper
ImportError: No module named ConfigurationWrapper
I tried to add empty __ init __.py file in the same folder but still nothing happens.
Try adding a dot (.) before the imported module
import .ConfigurationWrapper
or import your class
from .ConfigurationWrapper import ConfigurationWrapper
The dot (.) means that you're importing from the same directory.
The way I solved it was to add:
execfile("./ConfigurationWrapper")
but I'd like to know how appropriate is that.

Using python function from other python file and subsequent class?

I have been learning working with classes in python after learning OOPs in c++.
I am working on a project, where I have a class defined in one file, and an important function to be used in the class in the seperate file.
I have to call the class in the first file, but I am getting the ImportError.
Great, if you could help.
try1.py
from try2 import prnt
class a:
def __init__(self):
print("started")
def func1(self):
print("func1")
prnt()
try2.py
from try1 import a
b = a()
b.func1()
def prnt():
b.func()
As for eg, in the above example, when I am running try1.py, I am getting an ImportError: cannot import name 'prnt'.
You absolutely need to redesign your project. Even if you did manage to get away with the cyclic imports (ie by moving the import to inside the function - but don't do it) you will still get a NameError: name 'b' is not defined since b is not define in prnt.
Unless prnt can't be defined in class a (why?), consider defining prnt in a third, "utils" file and import it in both try1.py and try2.py and pass an object to it so it can access all of its attributes.
Just run your code, read the error, and deduct something from it.
When you run it, here is the error message :
Traceback (most recent call last):
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
File "C:\Users\Kilian\Desktop\Code\Garbage\temp2.py", line 1, in <module>
from tmp import a
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
ImportError: cannot import name prnt
Your script is trying to import something it already has tried to import earlier on. Python is probably deducing that it can't import it. :)

How do you import files into the Python shell?

I made a sample file that uses a class called Names. It has its initialization function and a few methods. When I create an instance of the class it retrieves the instance's first name and last name. The other methods greet the instance and say a departure message. My question is: how do I import this file into the Python shell without having to run the module itself?
The name of my file is classNames.py and the location is C:\Users\Darian\Desktop\Python_Programs\Experimenting
Here is what my code looks like:
class Names(object):
#first function called when creating an instance of the class
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
#class method that greets the instance of the class.
def intro(self):
print "Hello {} {}!".format(self.first_name, self.last_name)
def departure(self):
print "Goodbye {} {}!".format(self.first_name, self.last_name)
But I get the error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import classNames.py
ImportError: No module named classNames.py
I am not clear about what you expect and what you see instead, but the handling of your module works exactly like the math and any other modules:
You just import them. If this happens for the first time, the file is taken and executed. Everything what is left in its namespace after running it is available to you from outside.
If your code only contains just def, class statements and assignments, wou won't notice that anything happens, because, well, nothing "really" happens at this time. But you have the classes, functions and other names available for use.
However, if you have print statements at top level, you'll see that it is indeed executed.
If you have this file anywhere in your Python path (be it explicitly or because it is in the current working directory), you can use it like
import classNames
and use its contents such as
n = classNames.Names("John", "Doe")
or you do
from classNames import Names
n = Names("John", "Doe")
Don't do import classNames.py, as this would try to import module py.py from the package classNames/.

defining and using classes in modules for Python

I have the module Test.py with class test inside the module. Here is the code:
class test:
SIZE = 100;
tot = 0;
def __init__(self, int1, int2):
tot = int1 + int2;
def getTot(self):
return tot;
def printIntegers(self):
for i in range(0, 10):
print(i);
Now, at the interpreter I try:
>>> import Test
>>> t = test(1, 2);
I get the following error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
t = test(1, 2);
NameError: name 'test' is not defined
Where did I go wrong?
You have to access the class like so:
Test.test
If you want to access the class like you tried to before, you have two options:
from Test import *
This imports everything from the module. However, it isn't recommended as there is a possibility that something from the module can overwrite a builtin without realising it.
You can also do:
from Test import test
This is much safer, because you know which names you are overwriting, assuming you are actually overwriting anything.
Your question has already been answered by #larsmans and #Votatility, but I'm chiming in because nobody mentioned that you're violating Python standards with your naming convention.
Modules should be all lower case, delimited by underscores (optional), while classes should be camel-cased. So, what you should have is:
test.py:
class Test(object):
pass
other.py
from test import Test
# or
import test
inst = test.Test()
When you do import Test, you can access the class as Test.test. If you want to access it as test, do from Test import test.

Categories

Resources