I am currently learning python programming (and am a beginner at it). Currently I am stuck on files exercises (so these are set things I need to do, rather than doing whatever I want. Unfortunately, it also means I probably can't do any complicated (for me) shortcuts)
Currently using Python 3.2.2
I need two different programs. One is to input what the user types in (a name and a DOB) and put that into records in a list and write that into a binary file. The other is to read that file and print that into a table using padding.
Codes:
First
import pickle
class newperson():
def __init__(self):
self.name = ""
self.dob = ""
stop = False
people = []
print("When you want to stop just hit enter")
count = 0
while stop == False:
name = input("Please Enter the name: ")
if len(name) == 0:
stop = True
else:
people.append(newperson())
people[count].name = name
people[count].dob = input("Please enter their DOB: ")
count = count + 1
file = open("ex9.4.dat", "wb")
pickle.dump(people,file)
file.close()
Second:
import pickle
myfile = open("ex9.4.dat", "rb")
people = pickle.load(myfile)
print("{0:<15}{1}".format("Name","DOB"))
for item in people:
print("{0:<15}{1}".format(item.name,item.dob))
The problem is that I am getting the following error when trying to run the 2nd program:
AttributeError: 'module' object has no attribute 'newperson'
on
people = pickle.load(myfile)
Unfortunately, when I have looked for answers on the other questions, either none of the solutions have worked, don't apply to me or mostly just went WAAAY over my head.
What am I doing wrong?
Thanks in advance for the help.
When pickle loads the file it tries to creates newperson instances, but newpersonis not defined in the second program. To solve that problem, you could create a new file newperson.py just containing the definition of the class `newperson.py``
# newperson.py
class newperson():
def __init__(self):
self.name = ""
self.dob = ""
In both programs, import the class after the import or pickle:
from newperson import newperson
Alternatively, you could use a dictionary instead of the newperson class.
I think to unpickle (i.e. pickle.load) you have to have to class newperson somewhere in namespace. try importing class newperson into the module where you run pickle.load.
Related
Perhaps someone here can help me. I am trying to create a habit-tracking app as a project and I have created a habit class along with a habit creation function that I defined. Eventually, I want to be able to use a sqlite database to hold my data. I have not coded the database functionality yet, but I wanted to test my function to at least see if the logic works. Until now, this is what I have:
from datetime import date
class Habit:
def __init__(self, name: str, description: str):
self.name = name
self.description = description
def initiate_habit(self):
habit_name = input('Enter a habit name: ')
type = input('Enter a habit type: ')
duration = input("Enter habit duration (daily, weekly, monthly): ")
start_date = date.today()
end_date = input('Enter end date: ')
When I try to call my function, I get the following error:
NameError: name 'initiate_habit' is not defined
Can someone tell me where I'm going wrong?
To test:
habit = Habit('Read', 'Read 15 pages daily')
initiate_habit()
When I try running my initiate_habit function, I receive the below-mentioned error:
NameError: name 'initiate_habit' is not defined
`
The method, is an instance method, how could the code know initiate_habit is related to habit if you don't tell it
Shoule be
habit = Habit('Read', 'Read 15 pages daily')
habit.initiate_habit()
I have been using PyTest for some time now to write some simple tests (like the ones you find in tutorials and youtube video's) and I thought now it was time to start writing actual test for our python scripts. The scripts are way more advanced than any shown in tutorials so I am getting a bit stuck. I do not want the entire correct answer, but rather a nudge in the right direction if possible. Here is my issue:
We have a script that reads a .md text file and converts it to a pdf file based on an external template. Part of the script is here below (I removed most of it because I first just want to have 1 running test)
class DocumentationEngine:
def __init__(self, title, subtitle, series, style='TIIStyle_Digital_Aug_2020', templateFile='template.docet', tableOfContents=True, listOfFigures=False, listOfTables=False):
self.title = title
self.subtitle = subtitle
self.series = series
self.style = style
self.template = {}
self.hasTOC = tableOfContents
self.hasLOF = listOfFigures
self.hasLOT = listOfTables
self.loadTemplate(templateFile)
def loadTemplate(self, file='template.docet'):
with open(file, "r") as templatefile:
lines = templatefile.readlines()
key = "dummy"
value = ""
for line in lines:
line = line.strip()
if line.startswith('[') and line.endswith(']'):
self.template[key] = value
key = line[1:-1]
value = ""
else:
value += line + '\n'
def build(self, versions=[], content='', filename='Documenter\\_Autogenerated'):
document = self.template["doc"]
document = document.replace("%%style%%", self.style)
document = document.replace("%%body%%",
self.buildFirstPage() +
self.buildTableOfContents() +
self.buildListOfFigures() +
self.buildListOfTables() +
self.buildVersionTable(versions, filename) +
self.buildContentPages(content=content) +
self.buildLastPage()
)
return document
def buildLastPage(self):
return self.template["last_page"]
I am trying to write a simple unit test for the buildLastPage method and have been stuck for several days now.
I am not sure whether or not I need to mock the template file, use a fixture and/or if I can actually test only that method with all dependencies.
I started with the following:
from doceng import DocumentationEngine
import pytest
class Test:
def test_buildLastPage(self):
build_last_page = DocumentationEngine()
assert build_last_page.template(1) == 1
which gives me an error regarding 3 required arguments. When adding the arguments like this:
from doceng import DocumentationEngine
import pytest
class Test:
def test_buildLastPage(self, title, subtitle, series):
build_last_page = DocumentationEngine()
assert build_last_page.template(1) == 1
which gives me an error that the fixture is not found.
I added a fixture in conftest.py file like this:
import pytest
from doceng import DocumentationEngine
#pytest.fixture
def title(title):
return title("test")
which will get me another error, recursive dependency involving fixture 'title' detected
I'm quite stuck so any nudge in the right direction for a newbie would be highly appreciated
The error of the fixtures is regarding your test function test_buildLastPage. The way you are using it, it only needs the self argument.
A test function in pytest without any decorators always expects to find fixtures, that have the same name as the arguments. You did not define any fixtures and also do not use the arguments in your function. Therefore, you can remove them safely.
The actual error points DocumentationEngine(). The class expect 3 arguments when initializing the object. You set no arguments. Check your __init__ function again to find the proper arguments.
I have two files: client.py and ItemDatabase.py. I'm trying to store item values in a separate source file, similar to a database, and then call on those item values when I need them in other source files. Here I have the classes Item and WeaponData, which both hold information about the item, and then the instance itself is created in the ItemDatabase. When I want to get that information in the other source file through a print statement I am getting an error: NameError: name 'tinder_sword' is not defined, even though my IDE recognizes that tinder_sword is apart of ItemDatabase.
In client.py:
from ItemDatabase import *
import pygame as pg
class Item:
def __init__(self):
self.name = ""
self.description = ""
self.max_stack_size = 0
self.icon = ""
class WeaponData(Item):
def __init__(self):
super().__init__()
self.damage = 0
self.range = 0
self.cooldown = 0
self.max_condition = 0
self.max_stack_size = 1
print(tinder_sword.name)
In ItemDatabase.py:
from client import *
tinder_sword = WeaponData()
tinder_sword.name = "Tinder Sword"
tinder_sword.description = "Weak and flimsy, but it's not bad for a starter weapon."
tinder_sword.damage = 10
tinder_sword.cooldown = 0.2
tinder_sword.max_condition = 75
Hey! So the issue with your code is not that the variable is not getting imported. The issue is that you are importing client into ItemDatabase.py and then importing ItemDatabase into client.
When you import a python file all the code that is not in a scope gets run. So if you follow the logic:
in client.py
from ItemDatabase import *
so now we run the code in ItemDatabase
from client import *
so now we run the code in client
But now python has already imported ItemDatabase so it skips it.
Now we create the 2 classes in client.py and we run the last line of code:
print(tinder_sword.name)
Except. We have not actually run the code to create tinder_sword yet. Because we are still in the phase of importing client into ItemDatabase.
Importing files needs to flow one way, like a river. If you need two files to use data from each other then you can create a class called Populater in file2. File 1 imports Populator, gives it the values that file 2 needs, and then exits. File 2 never needs to import file 1 but it's populate class will still have file 1's values. This is like sending a power boat up the river to fetch some logs and the driving the boat back down the river to be used there.
This is however not a good way to write programs! It usually means that the way you are thinking about your application is too intertwined and will probably lead to more bugs like this down the line.
The "Nice" way to write a program like this is to do what is called "Separation of concerns". One file focuses on doing one thing only. But doing that one thing well. For example: You might have a SwordBuilder file. It creates amazing swords. Then you might have a storage class. It is focused on storing and reading any items you might have to the filesystem so your games can be saved.
Hope this helps!
trying to help here, usually I would create a config.py file contain classes and stuff as what you have in client.py
then import it in doSomething.py then do the printing in there
import pygame as pg
class Item:
def __init__(self):
self.name = ""
self.description = ""
self.max_stack_size = 0
self.icon = ""
class WeaponData(Item):
def __init__(self):
super().__init__()
self.damage = 0
self.range = 0
self.cooldown = 0
self.max_condition = 0
self.max_stack_size = 1
import client.py
tinder_sword = client.WeaponData()
tinder_sword.name = "Tinder Sword"
tinder_sword.description = "Weak and flimsy, but it's not bad for a starter weapon."
tinder_sword.damage = 10
tinder_sword.cooldown = 0.2
tinder_sword.max_condition = 75
print(tinder_sword.name)
windows 10 - python 3.5.2
Hi, I have the two following python files, and I want to edit the second file's variables using the code in the first python file.
firstfile.py
from X.secondfile import *
def edit():
#editing second file's variables by user input
if Language == 'en-US':
print('language is English-us')
elif Language == 'en-UK':
print('language is English-uk')
secondfile.py
Language = 'en-US'
i can add some variables to it by following code, but how can i edit one ?
with open("secondfile.py","a") as f:
f.write("Language = 'en-US'")
Any ideas how to do that?
You can embed the Language in a class in the second file that has a method to change it.
Module 2
class Language:
def __init__(self):
self.language = 'en-US'
def __str__(self):
return self.language
def change(self, lang):
assert isinstance(lang, str)
self.language = lang
language = Language()
Then import the "language," and change it with the change method.
Module 1
from module2 import language
print(language)
language.change("test")
print(language)
This can be done to edit a variable in another file:
import X.secondfile
X.secondfile.Language = 'en-UK'
However, I have two suggestions:
Don't use import * - it pollutes the namespace with unexpected
names
Don't use such global variables, if they are not constants. Some code will read the value before it is changed and some afterwards. And none will expect it to change.
So, rather than this, create a class in the other file.
class LanguagePreferences(object):
def __init__(self, langcode):
self.langcode = langcode
language_preferences = LanguagePreferences('en-UK')
I am working on a small project and I am not sure if the error I am getting is due to the IDLE I am using or something I am doing wrong.
I am using OOP in python running on the Wing IDLE. I have the latest version of the python shell running on a Windows 8 PC.
In my program I have a method that takes user input and using that input it creates the parameters required to create a shelf.
'def subject_creator(self):
subject_name = input("Enter the subject name:")
subject_file = subject_name + "file"
name = subject_name
return subject_name, subject_file, name'
Ideally the program would then use the three returned statements namely subject_name, subject_file, and name in opening the new shelf.
'def __init__(self, subject_name, subject_file, name ):
subject_name = shelve.open ("subject_file", "c")
self.name = name
print("The", self.name ,"note has been created")'
while True:
print ("""
1.Create new note
2.Add new term
3.Look up term
4.Exit/Quit
""")
ans= input("What would you like to do?: ")
if ans=="1":
subject_creator()
note = Notebook(subject_name, subject_file, name)
subject_name.sync()
However when I run the program and in my main menu I select choice 1 which runs the code above, I receive and error that states.
<module>
builtins.TypeError: subject_creator() missing 1 required positional argument: 'self'
This is somewhat puzzling as I include the self parameter when I wrote the code for subject creator as shown above. Other than this I have no other errors.
Any feedback would be greatly appreciated.
You are confusing "function" and "method".
In Python, a method is a function defined inside a class scope, and it will receive the object as its implicit first argument:
class Example:
def try_me(self):
print "hello."
You would use it like this:
x = Example()
x.try_me()
and try_me() will receive x as its first (here, ignored) argument. This is useful so that the method can access the object instance's attributes etc.
Contrast this with a regular function, i.e. one defined outside of a class:
def try_me_too():
print "hello."
which is simply invoked like
try_me_too()
Tangentially, your example code does not pick up the values returned by your subject_creator function:
> if ans=="1":
> subject_creator()
> note = Notebook(subject_name, subject_file, name)
The scope where this happens doesn't have variables named subject_name etc. You need to create them somehow.
if ans=="1":
ick, bar, poo = subject_creator()
note = Notebook(ick, bar, poo)
(I chose nonsense variable names mainly to emphasize that these are different from the variables defined, and only available, inside subject_creator.)
Just to complete this, here is a demonstration of how self is useful.
class Otherexample:
def __init__(self, greeting):
self.greeting = greeting
def try_me_also(self):
print self.greeting
use like this:
y = Otherexample("hello.")
y.try_me_also()
Here, the greeting is a property of the object we created; the __init__ method receives it as its argument, and stores it as an attribute of the instance. The try_me_also method uses self to fetch this attribute, and print it.
This line causes your error
subject_creator()
You should change
def subject_creator(self):
subject_name = input("Enter the subject name:")
subject_file = subject_name + "file"
name = subject_name
return subject_name, subject_file, name
to
def subject_creator():
subject_name = raw_input("Enter the subject name:")
subject_file = subject_name + "file"
name = subject_name
return subject_name, subject_file, name
You don't need a parameter in your function if you won't use it.
Also,if you are using python 2.x, consider using raw_input() and not input(). For more info, please read differences between input() and raw_input().