class Rating():
def __init__(self, user, item, rating):
self.user = user
self.item = item
self.rating = rating
def __str__(self):
return str(user) + " " + str(item) + " " + str(rating)
def __repr__(self):
return str(user) + " " + str(item) + " " + str(rating)
data = open('data.dat').readlines()
records = ()
for i in data:
user, item, rating = i.split()
r = Rating(user, item, rating)
records += (r,)
print records
data = [A, B, C], I'd expect records to have (<Record> A, <Record> B, <Record> C). But instead it contains (<Record> C, <Record> C, <Record> C)?
You are not using the class attributes, but the global variables you have defined by chance.
return str(user) + " " + str(item) + " " + str(rating)
Should look like
return str(self.user) + " " + str(self.item) + " " + str(self.rating)
Your class's __str__ is reference global names:
def __str__(self):
return str(user) + " " + str(item) + " " + str(rating)
Which will be the last iteration of:
user, item, rating = i.split()
That needs to be fixed to be self.user, self.item etc...
Also I would change your line to be the more efficient and Pythonic:
records = [Rating(*line.split()) for line in data]
Related
I need the below str method written to return a string rather than print a string.
def __str__(self):
"""Returns the string representation of the student."""
avg = sum(self.scores) / len(self.scores)
print("Name: " + str(self.name))
print("Score 1: " + str(self.scores[0]))
print("Score 2: " + str(self.scores[1]))
print("Score 3: " + str(self.scores[2]))
print("High: " + str(int(max(self.scores))))
print("Average: %.2f\n" % avg)
What you want to do is convert all those print statements into one string, while maintaining the newlines that you already have.
Something like this should work in place of str
def __str__(self):
avg = sum(self.scores) / len(self.scores)
s = ""
s += "Name: " + str(self.name) + "\n"
s += "Score 1: " + str(self.scores[0]) + "\n"
s += "Score 2: " + str(self.scores[1]) + "\n"
s += "Score 3: " + str(self.scores[2]) + "\n"
s += "High: " + str(int(max(self.scores))) + "\n"
s += "Average: %.2f\n" % avg + "\n"
return s
I have been learning python for 2 days.
So I am making this program which generates different numbers, and adds them to a string.
I have a function for getting the random numbers:
def GetRandomNumbers():
random_number = random.choice(zero_to_nine)
two_random_number = random.choice(zero_to_nine)
three_random_number = random.choice(zero_to_nine)
four_random_number = random.choice(zero_to_nine)
//
def SettingVariables():
first_combination = ("__asm _emit " + zero + ("x") + random_number + " " + "/")
two_first_combination = ("__asm _emit " + zero + ("x") + two_random_number + " " + "/")
three_first_combination = ("__asm _emit " + zero + ("x") + three_random_number + " " + "/")
four_first_combination = ("__asm _emit " + zero + ("x") + four_random_number + " " + "/")
And then when I attempt to use theese generated variables in a different function where theese numbers are added onto text it is unidentified. I know it has something to do with global variables, but I would need some explaining.
Propably you should return values from your first function:
def GetRandomNumbers():
... # get your numbers
return random_number, two_random_number, ...
Then you can parse these numbers as an argument to your second function:
def SettingVariables(first_num, second_num, third_num): ...
You could set a global variable like this (this is not recommended):
global var
var = 1
Your code could look like this:
def GetRandomNumbers():
random_number = random.choice(zero_to_nine)
two_random_number = random.choice(zero_to_nine)
three_random_number = random.choice(zero_to_nine)
four_random_number = random.choice(zero_to_nine)
return random_number, two_random_number, three_random_number, four_random_number
def SettingVariables(random_number, two_random_number, three_random_number, four_random_number):
first_combination = ("__asm _emit " + zero + ("x") + random_number + " " + "/")
two_first_combination = ("__asm _emit " + zero + ("x") + two_random_number + " " + "/")
three_first_combination = ("__asm _emit " + zero + ("x") + three_random_number + " " + "/")
four_first_combination = ("__asm _emit " + zero + ("x") + four_random_number + " " + "/")
# later in the program
nums = GetRandomNumbers()
SettingVariables(nums[0], nums[1], nums[2], nums[3]) # could also use *nums
Note that your SettingVariables function should also return the "combinations". You then can use the same principle
It's interesting that you're function names contains keyword get and set. These are concept familiar to classes.
You may consider define some classes here.
An example would be
class RandomNumbers:
def __init__(self, zero_to_nine):
random_number = random.choice(zero_to_nine)
class Variables:
def __init__(self, random_numbers):
self.first_combination = ("__asm _emit " + zero + ("x") + random_numbers.random_number + " " + "/")
...
Then you can do like this:
random_numbers = RandomNumbers()
variables = Variables(random_numbers)
print(variables.first_combination)
[edit]
I suggested classes as it seems that you'are using functions as initializers. They are quite similar to what in OOP are object constructors.
This would avoid the need for declaring all a bunch of variables outside of the function, update them an returning from the function.
I am trying to call a function with a string but as I do so the function just make use of the name of the argument for that function.
My function is defined as sortering(attribut) and when i call it with for example: sortering('age') it uses 'attribut' and not 'age'.
Here is the code, I am fairly new to python so it is probably something obvious that I am not familiar with.
def sortering(attribut):
try:
val1 = input("Vill du sortera stigande eller fallande? s/f")
if val1 == "s":
djurlista.sort(key=lambda x: x.attribut)
print(*djurlista,sep='\n' + ' ' + '\n')
elif val1 == "f":
djurlista.sort(key=lambda x: x.attribut, reverse=True)
print(*djurlista,sep='\n' + ' ' + '\n')
except ValueError:
print("Svara med s för stigande eller f för fallande!")
sortering('age')
The list "djurlista" is a list of strings and each string is an object 'Djur' with attributes: art, namn, ålder, kön, gravid
Here is that code:
class Djur:
def __init__(self, art, namn, ålder, kön, gravid):
self.art = art
self.namn = namn
self.age = ålder
self.gender = kön
self.gravid = gravid
x = Djur(art, namn, ålder, kön, gravid)
self.djurlista.append(x)
def __str__(self):
return ("Art: " + str(self.art) + " " + "\n"
"Namn: " + str(self.namn) + " " + "\n"
"Ålder: " + str(self.age) + " " + "\n"
"Kön: " + str(self.gender) + " " + "\n"
"Gravid: " + str(self.gravid))
def __repr__(self):
return str(self)
Instead of x.attribut (where attribut is a string, and x is a Djur instance), you should use [Python 3.Docs]: Built-in Functions - getattr(object, name[, default]):
djurlista.sort(key=lambda x: getattr(x, attribut))
Use x[attribut] and not x.attribut
def sortering(attribut):
try:
val1 = input("Vill du sortera stigande eller fallande? s/f")
if val1 == "s":
djurlista.sort(key=lambda x: x[attribut])
print(*djurlista,sep='\n' + ' ' + '\n')
elif val1 == "f":
djurlista.sort(key=lambda x: x[attribut], reverse=True)
print(*djurlista,sep='\n' + ' ' + '\n')
except ValueError:
print("Svara med s för stigande eller f för fallande!")
sortering('age')
It appears that you're trying to get the .attribut parameter from a global class/obj called x (via x.attribut), which should be throwing an error if it doesn't exist, but may not be if it's stored in your python cli somehow.
If you remove the x. before the reference to attribut, do you still get the same error?
I am writing a program that keeps track of the animals on a farm and I want to be able to search for an animal by e.g: name, gender, age etc, which all are attributes to the objects. I am a complete noob when it comes to Python so all help is very appreciated.
Here is the code i have so far for this, but it only ads the attribute that is searched for to the list and then prints it. I want to be able to add the entire object to the list and print the whole object through that list.
class Djur:
def __init__(self, art, namn, ålder, kön, gravid):
self.art = art
self.namn = namn
self.age = ålder
self.gender = kön
self.gravid = gravid
def __str__(self):
return ("Art: " + str(self.art) + " " + "\n"
"Namn: " + str(self.namn) + " " + "\n"
"Ålder: " + str(self.age) + " " + "\n"
"Kön: " + str(self.gender) + " " + "\n"
"Gravid: " + str(self.gravid))
def __repr__(self):
return str(self)
try:
val2 = input("Ange sök-text")
l=[]
for x in djurlista:
y = x.art or x.gender or x.namn or x.gravid or x.age
if y == val2:
l.append(x.art)
print(l)
meny()
except ValueError:
print("Var god välj ett giltigt alternativ!")
To create a list with the objects you just need to write l.append(x) instead of l.append(x.art). Now you are just appending the property art.
Below is my code. It is giving me a compile error saying that artist has not been defined. This confuses me since artist is a parameter I'm passing.
Thanks.
class Track:
def __init__(self, artist, title, album=None):
self.artist = str(artist)
self.title = str(title)
self.album = album
def __str__(self):
return self.artist + " " + self.title + " " + self.album
def set_album(self, album):
self.album = album
class Album:
def init(self, artist, title, year='', genre='', tracks=None):
self.artist = str(artist)
self.title = str(title)
self.year = str(year)
self.genre = str(genre)
self.tracks = tracks
def __str__(self):
return self.artist + " " + self.title + " " + self.year + " " + self.genre + " " + self.tracks
def add_track(track):
self.tracks.append(track)
def music_library(tracks, albums):
while true:
command = raw_input("Please enter a command (s, st or sa)").lower()
if "s " in command:
searchText = command.split()(1)
elif "sa " in command:
searchText = command.split()(1)
elif "st " in command:
searchText = command.split()(1)
import os
from mutagen.mp3 import MP3
def load_library(dir):
for root, dirs, files in os.walk("."):
for filename in files:
if filename.lower().endswith(".mp3"):
fullname = os.path.join(root, filename)
print "\n%s" % fullname
try:
audio = MP3(fullname)
for key in audio:
print " %s: %s" % (key, str(audio[key]))
except:
print "Error on %s" % fullname
That is the entire file. I am running it using
python musiclib.py
I suspect it's because you're mixing tabs and spaces. When I copy and paste your code and look at it, I see:
' class Track:'
' \tdef __init__(self, artist, title, album=None):'
' \t\tself.artist = str(artist)'
' self.title = str(title)'
' self.album = album'
' '
' \tdef __str__(self):'
' \t\treturn self.artist + " " + self.title + " " + self.album'
' '
' \tdef set_album(self, album):'
' \t\tself.album = album'
Mixing tabs and spaces confuses Python about how far code is indented. Switch to using four spaces for indentation, and run your code using python -tt yourprogramname.py to confirm this diagnosis.