I am getting the NameError anytime i create an instance/object from a class Person
i have created a class saved as Person.py
on the terminal i have imported everything using 'python -i'
i typed P1=Person("name","name",20)
but i got the following error
python -i
Python 2.7.15+ (default, Nov 27 2018, 23:36:35)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> p1=Person("i","j",20)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Person' is not defined
Code:
class Person:
#constructor
def __init__(self,first_name,last_name,age):
self.first_name = first_name
self.last_name = last_name
self.age = age
#set first_name
def setFirst_name(self,first_name):
self.first_name = first_name
#get first_name
def getFirst_name(self):
return self.first_name
#set last_name
def setLast_name(self,last_name):
self.last_name = last_name
#get last_name
def getLast_name(self):
return self.last_name
#set age
def setAge(self,age):
self.age = age
#get age
def getAge(self):
return self.age
#get full_name
def getFull_name(self):
return self.first_name + " " + self.last_name
#get details
def getDetails(self):
details = {'First Name':self.first_name,'Last Name':self.last_name,'Age':self.age}
i expected P1 to create an object of Person so that when i call the function 'getDetails()' it should print the follow
First Name:i Last Name: j Age: 20
You have to import a local file before you can use it - even if that file is in the same directory. This should work:
>>> import Person
But now, Person represents the contents of the file Person.py. To actually get to the Person class, you'll need to invoke it explicitly:
>>> p1 = Person.Person("i", "j", 20)
You can get around this by importing the class Person from the file Person.py:
>>> from Persion import Person
>>> p1 = Person("i", "j", 20)
So you're just running a python shell in the working directory where the Person.py file you wrote is located?
This isn't enough to tell the shell/Python that you want to use that file's content. Anything not already defined in that shell instance must be explicitly imported. (with correct capitalisation)
If you're working directly on the shell with -i then you must include arguments to go after that. Those being the file names you want, so your full line will be python -i "Person.py".
If in future however you want to work in a script then this isn't possible and you'll need to specify imports in the "main" file you're working in and require your other files to be called to.
e.g.
#import ModuleName
# in this case your "module" is the "Person.py" file so:
import Person
This will then allow you to use the content of that "module"/file from the shell/script you're working in. To use your Class that is inside that module, which is also named "Person", you'll need to reference to it like Person.Person(args)
Of course that extra writing is going be annoying to look at so we can clean it up by importing specifically that Class as so:
#from Module import Class
from Person import Person
# now we can just use Person(args) without having to specify the Person module every time
For future reference, as I assume you're learning about Classes:
If you have several classes inside a single module/file, say you added an Animal Class, then you can import them one by one, or all of them at once with an asterisk like so:
#either
from Person import Person, Animal
#or
from Person import *
Related
I have three files that all contain classes with the same names but slightly different definitions. Some methods in these classes are identical across all three files, so I abstracted them out to another file, utils.py, where they are defined within a "template" version of the original class. The problem is that these methods invoke functions and modules that exist in the original files but not this new one.
My original approach was to use multiple class inheritance, which would initialize the template class within the scope of the parent class, allowing access to all the functions and modules it requires. However, I was instructed to avoid multiple class inheritance and to simply import the utils file.
Importing does not apply the same scoping logic as mentioned above with inheritance. So here arises my problem. I have created a small example to show what I mean. I am using a module called datajoint. You don't need to know much about it except that a schema is basically a table or collection of tables in a database.
schemas.py
import datajoint as dj
from datetime import datetime
import utils
dj.conn()
schema = dj.Schema('adib_example1')
schema.drop()
schema = dj.Schema('adib_example1')
def test_print():
print("test")
#schema
class Subject(dj.Lookup):
definition = """
subject_id: int
"""
contents = [dict(subject_id=1)]
#schema
class Session(dj.Computed):
definition = """
-> Subject
time: varchar(30)
"""
def make(self, key):
utils.SessionTemplate.make(self,key)
Session.populate() # invokes Session's make(), passing Subject's primary key
Approach 1
Import scoping not working like inheritance
utils.py
class SessionTemplate():
#staticmethod
def make(table, key):
test_print() # parent function usage example
table.time = f"{datetime.now()}" # parent module usage example
new_entry = dict(**key, time=table.time)
table.insert1(new_entry)
error
Traceback (most recent call last):
File "/home/.anaconda/imported_make/schemas.py", line 30, in <module>
Session.populate() # invokes Session's make(), passing Subject's primary key
File "/opt/conda/lib/python3.9/site-packages/datajoint/autopopulate.py", line 153, in populate
make(dict(key))
File "/home/.anaconda/imported_make/schemas.py", line 28, in make
utils.SessionTemplate.make(self,key)
File "/home/.anaconda/imported_make/utils.py", line 5, in make
test_print() # parent function usage example
NameError: name 'test_print' is not defined
Approach 2
Importing schemas.py into utils.py works, but requires including schemas. before every imported function and module, which is not practical in my case.
utils.py
import schemas
class SessionTemplate():
#staticmethod
def make(table, key):
schemas.test_print() # parent function usage example
table.time = f"{schemas.datetime.now()}" # parent module usage example
new_entry = dict(**key, time=table.time)
table.insert1(new_entry)
Approach 3
Import using * to avoid having to add schemas. before each parent function/module somehow does not provide access to the parents modules and functions.
from schemas import *
class SessionTemplate():
#staticmethod
def make(table, key):
test_print() # parent function usage example
table.time = f"{datetime.now()}" # parent module usage example
new_entry = dict(**key, time=table.time)
table.insert1(new_entry)
error
Traceback (most recent call last):
File "/home/.anaconda/imported_make/run.py", line 1, in <module>
import schemas
File "/home/.anaconda/imported_make/schemas.py", line 30, in <module>
Session.populate() # invokes Session's make(), passing Subject's primary key
File "/opt/conda/lib/python3.9/site-packages/datajoint/autopopulate.py", line 153, in populate
make(dict(key))
File "/home/.anaconda/imported_make/schemas.py", line 28, in make
utils.SessionTemplate().make(self,key)
File "/home/.anaconda/imported_make/utils.py", line 7, in make
test_print() # parent function usage example
NameError: name 'test_print' is not defined
I know import * is bad practice, but it would have been fine in this instance if it worked, and I'm not sure why it doesn't.
boss.py
class tasks():
def job1(input):
// do something
return output
def job2(input):
// do something
return output
worker.py
import boss.tasks
from boss.tasks import job1, job2
input_value = "xyz"
output1 = boss.tasks().job1(input_value)
output2 = boss.tasks().job2(input_value)
I just started writing some code in python using the randominfo library
https://pypi.org/project/randominfo/
In my code I have:
from randominfo import get_email, Person
get_email(Person = None)
I get the following error:
TypeError: get_email() got an unexpected keyword argument 'Person'
I am calling it exactly the way it is in the documentation but I get this error. I am using pycharm IDE with python 3.8. I cannot figure out why this happens.
I found instantiating the Person object first to work for me.
import randominfo as ri
class Person:
def __init__(self) -> None:
self.first_name = ri.get_first_name()
self.last_name = ri.get_last_name()
self.birthdate = ri.get_birthdate()
person1 = Person()
print(ri.get_email(person1))
I am very new to python so please try keep answers very simple, as I struggle to understand the answers on similar questions. I have the file Employee.py
class Person:
def __init__(self,name,job):
self.name = name
self.job =job
def getEmployeeDescription(self):
return self.name + " is a " + self.job
This is stored on my desktop. I want to import this into cmd so I can do for example
p = Person("James","Builder")
p.name
Python works on cmd, I just dont know exactly what needs to be typed in to allow me to access this class. I tried cd Desktop > python employee.py, but this just runs the file whereas I want to be able to use the class
Open a Python REPL by typing python into the command line
Import the appropriate class that you want to use
Use the class as needed
Here's an example:
$python3
>>> from employee.py import Person
>>> person = Person('name', 'job')
Please don't mark as duplicate, other similar questions did not solve my issue.
This is my setup
/main.py
/actions/ListitAction.py
/actions/ViewAction.py
Main.py:
from actions import ListitAction, ViewAction
ListitAction.py:
class ListitAction(object):
def __init__(self):
#some init behavior
def build_uri():
return "test.uri"
ViewAction.py
from actions import ListitAction
class ViewAction(ListitAction):
def __init__(self, view_id):
ListitAction.__init__(self)
self.view_id = view_id
def build_uri():
return "test"
Running:
$ python3 main.py
The only error message I receive is:
Traceback (most recent call last):
File "/home/jlevac/workspace/project/listit.py", line 11, in <module>
from actions import ListitAction, ViewAction, CommentsAction
File "/home/jlevac/workspace/project/actions/ViewAction.py", line 3, in <module>
class ViewAction(ListitAction):
TypeError: module.__init__() takes at most 2 arguments (3 given)
Even if I try for the python3 console, I received the same error message:
$python3
from actions import ViewAction
I am new to Python, but not new to programming. I'm assuming that my error messages have to do with the import statements, but based on the message I can't really figure out what it means.
Your imports are wrong, so you're trying to inherit from the modules themselves, not the classes (of the same name) defined inside them.
from actions import ListitAction
in ViewAction.py should be:
from actions.ListitAction import ListitAction
and similarly, all other uses should switch to explicit imports of from actions.XXX import XXX (thanks to the repetitive names), e.g. from actions import ListitAction, ViewAction must become two imports:
from actions.ListitAction import ListitAction
from actions.ViewAction import ViewAction
because the classes being imported come from different modules under the actions package.
You are passing self when you don't need to, that's all.
Edit: see MSeifert's comment answer since I don't want to steal content.
If your file is in the root directory of the project then you can directly write the file name and import.
For example, if filename is Parent1.py and class name is Parent, then you would write
from Parent1 import Parent
However, if your file Parent1.py is under any folder for example:
DemoFolder -> Parent1.py- > Parent
(Folder). (File). (Class name)
Then you would have to write:
from Test.Parent1 import Parent
Creating classes and instance of variables
class Student:
# Creating a Class Variables
perc_Raise = 1.05
# Creating a constructor or a special method to initialize values
def __init__(self,firstName,lastName,marks):
self.firstName = firstName
self.lastName = lastName
self.email = firstName + "." + lastName +"#northalley.com"
self.marks = marks
def fullName(self):
return '{} {}'.format(self.firstName,self.lastName)
def apply_raise(self):
self.marks = int(self.marks * self.perc_Raise)
Creating a two instance variable for a Student class
std_1 = Student('Mahesh','Gatta',62)
std_2 = Student('Saran','D',63)
print(std_1.fullName())
print(std_1.marks)
std_1.apply_raise()
print(std_1.marks)
print(std_1.email)
print(std_1.__dict__)
print(std_2.fullName())
print(std_2.marks)
std_2.apply_raise()
print(std_2.marks)
print(std_2.email)
print(std_2.__dict__)
print(Student.__dict__)
Inheritance
class Dumb(Student):
perc_Raise = 1.10
def __init__(self,firstName,lastName,marks,prog_lang):
super().__init__(firstName,lastName,marks)
self.prog_lang = prog_lang
std_1 = Dumb('Suresh','B',51,'Python')
print(std_1.fullName())
print(std_1.marks)
std_1.apply_raise()
print(std_1.marks)
print(std_1.prog_lang)
How do I import a Python file and use the user input later?
For example:
#mainprogram
from folder import startup
name
#startup
name = input('Choose your name')
What I want is to use the startup program to input the name, then be able to use the name later in the main program.
You can access that variable via startup.name later in your code.
name will be in startup.name. You can use dir(startup) to see it.
Or, as an alternate solution:
# Assuming from the names that 'folder' is a folder and 'startup' is a Python script
from folder.startup import *
now you can just use name without the startup. in front of it.
I think is better do your code in classes and functions.
I suggest you to do:
class Startup(object):
#staticmethod
def getName():
name = ""
try:
name = input("Put your name: ")
print('Name took.')
return True
except:
"Can't get name."
return False
>> import startup
>> Startup.getName()