output is not printing string in python - python

i have made a program but the output that i'm getting is
(<q3v3.Student instance at 0x023BB620>, 'is doing the following modules:', ' <q3v3.Module instance at 0x023BB670> <q3v3.Module instance at 0x023BB698>')
For example , the above output should give me Alice is doing following module : biology, chemistry
Help
this is my full code:
class Student :
def __init__(self,students):
self.students= students
print self.students
#def __str__(self): # when i used this i've got error type TypeError: __str__ returned non-string (type NoneType)
#print str(self.students)
class Module:
def __init__(self,modules):
self.modules = modules
print self.modules
#def __str__(self):
#print str(self.modules)
class Registrations (Student,Module):
def __init__(self):
self.list= []
self.stulist = []
self.modulist= []
def __iter__(self):
return iter(self.list)
def __str__(self):
return str(self.list)
def add(self,students,modules):
self.list.append((students,modules))
#print (self.list)
def students(self,modules):
for i in self.list:
if i[1] == modules:
self.modulist.append((i[0]))
return iter(self.modulist)
def __str__(self):
return str(self.students)
def modules(self,students):
for i in self.list:
if i[0] == students:
self.stulist.append((i[1]))
return iter(self.stulist)
def __str__(self):
return str(self.modules)
i need to import my program to be able to run it to this :
from q3v4 import *
james = Student('james')
alice = Student('alice')
mary = Student('mary')
agm = Module('agm')
ipp = Module('ipp')
r = Registrations()
r.add(james,agm)
r.add(alice,agm)
r.add(alice,ipp)
mstr = ''
for m in map(str,r.modules(alice)):
mstr = mstr+' '+m
print(alice, 'is doing the following modules:', mstr)
sstr = ''
for s in map(str,r.students(agm)):
sstr = sstr+' '+s
print(agm, 'has the following students:', sstr)
print(r)

You could define a __str__ method in your Student class, and do something like this:
def __str__(self):
return self.name # Here the string you want to print

Are you using Python 2? If so, print is a keyword, not a function. There are two ways to solve your problem:
Write print foo, bar instead of print(foo, bar).
The difference is that print(foo, bar) is actually printing out the tuple (foo, bar), which uses the repr() representation of each element, rather than its str().
At the very top of your file, write from __future__ import print_function. This will magically convert print from a keyword into a function, causing your code to work as expected.
If you are using Python 3, my answer is irrelevant.

Related

__init__ and __str__ to handle files

I have a text file a.txt. I want to perform some preprocess on it like remove punct. and split it into words.
I have written the following code to perform few operations.
class pre:
def __init__(self,textfilepath):
self.textfilepath = textfilepath
def __str__(self,textfilepath):
return str(textfilepath)
def process(textpathfile):
with open(textpathfile, r) as abc:
a = abc.translate(string.maketrans("",""), string.punctuation)
a = a.split(' ')
return a
pre("a.txt")
I tried executing it.But it gave an error pre doesn't take arguments. Can any one help me with how to do this? Thanks all.
You shouldn't pass arguments to __str__. Instead you can access them through the properties of self:
class pre:
def __init__(self,textfilepath):
self.textfilepath = textfilepath
def __str__(self):
return self.textfilepath
def process(self):
with open(self.textfilepath, r) as abc:
a = abc.translate(string.maketrans("",""), string.punctuation)
a = a.split(' ')
return a
p = pre("a.txt")
print(p)
filedata = p.process()
print(filedata)

Get function object of caller in Python 2.7?

In playing with inspect and reading the other questions here, I still cannot figure out how to get the function object of the caller more cleanly than to load the module by its path and then find the function within that.
In other words, how would you complete the following so that caller() returns a method object?
import inspect
def caller():
frame = inspect.stack()[2]
code = frame[0]
path = frame[1]
line = frame[2]
name = frame[3] # function NAME string
# TODO: now what?
return func
def cry_wolf():
func = caller()
print "%s cried 'WOLF!'" % (func.__name__,)
def peter():
cry_wolf()
Remember, I already know the function name but what I'm trying to access is the function object that the calling code is running in. The result desired is:
peter cried 'WOLF!'
DONE! Thanks to user 61612, I have completed this code:
import imp, inspect, sys
def caller():
frame = inspect.stack()[2]
code = frame[0]
path = frame[1]
line = frame[2]
name = frame[3]
return code.f_globals[name]
def cry_wolf():
func = caller()
print "%s cried 'WOLF!'" % (func.__name__,)
def peter():
cry_wolf()
Awesome!
Frame objects have the f_globals attribute:
import inspect
def caller():
tup = inspect.stack()[2]
return tup[0].f_globals[tup[3]] # <function peter at address>
def cry_wolf():
func = caller()
print("%s cried 'WOLF!'" % (func.__name__,)) # peter cried 'WOLF!'
def peter():
cry_wolf()

Printing an object python class

I wrote the following program:
def split_and_add(invoer):
rij = invoer.split('=')
rows = []
for line in rij:
rows.append(process_row(line))
return rows
def process_row(line):
temp_coordinate_row = CoordinatRow()
rij = line.split()
for coordinate in rij:
coor = process_coordinate(coordinate)
temp_coordinate_row.add_coordinaterow(coor)
return temp_coordinate_row
def process_coordinate(coordinate):
cords = coordinate.split(',')
return Coordinate(int(cords[0]),int(cords[1]))
bestand = file_input()
rows = split_and_add(bestand)
for row in range(0,len(rows)-1):
rij = rows[row].weave(rows[row+1])
print rij
With this class:
class CoordinatRow(object):
def __init__(self):
self.coordinaterow = []
def add_coordinaterow(self, coordinate):
self.coordinaterow.append(coordinate)
def weave(self,other):
lijst = []
for i in range(len(self.coordinaterow)):
lijst.append(self.coordinaterow[i])
try:
lijst.append(other.coordinaterow[i])
except IndexError:
pass
self.coordinaterow = lijst
return self.coordinaterow
However there is an error in
for row in range(0,len(rows)-1):
rij = rows[row].weave(rows[row+1])
print rij
The outcome of the print statement is as follows:
[<Coordinates.Coordinate object at 0x021F5630>, <Coordinates.Coordinate object at 0x021F56D0>]
It seems as if the program doesn't acces the actual object and printing it. What am i doing wrong here ?
This isn't an error. This is exactly what it means for Python to "access the actual object and print it". This is what the default string representation for a class looks like.
If you want to customize the string representation of your class, you do that by defining a __repr__ method. The typical way to do it is to write a method that returns something that looks like a constructor call for your class.
Since you haven't shown us the definition of Coordinate, I'll make some assumptions here:
class Coordinate(object):
def __init__(self, x, y):
self.x, self.y = x, y
# your other existing methods
def __repr__(self):
return '{}({}, {})'.format(type(self).__name__, self.x, self.y)
If you don't define this yourself, you end up inheriting __repr__ from object, which looks something like:
return '<{} object at {:#010x}>'.format(type(self).__qualname__, id(self))
Sometimes you also want a more human-readable version of your objects. In that case, you also want to define a __str__ method:
def __str__(self):
return '<{}, {}>'.format(self.x, self.y)
Now:
>>> c = Coordinate(1, 2)
>>> c
Coordinate(1, 2)
>>> print(c)
<1, 2>
But notice that the __str__ of a list calls __repr__ on all of its members:
>>> cs = [c]
>>> print(cs)
[Coordinate(1, 2)]

make __str__ or __repr__ return list as string

I'm using python 3.3.4. Here is my code:
class ojaxi(object):
nomeri = 0
def __init__(self):
self.wevri = []
def damateba(self, adamiani):
if adamiani in self.wevri:
print("We Already Have That one")
else:
self.wevri.append(adamiani)
def __repr__(self):
return self.wevri
class adamiani(ojaxi):
def __init__(self, saxeli, shuasax, asaki):
self.saxeli = saxeli
self.shuasax = shuasax
self.asaki = asaki
def __str__(self):
return self
baramidze = ojaxi()
N1 = adamiani("tyler", "durden", 18)
N2 = adamiani("joe", "black", 20)
baramidze.damateba(N1)
baramidze.damateba(N2)
print(baramidze)
Problem i have is that i can't make a function print out all the members in "baramidze". I want __repr__ or __str__ to print out something like this:
["N1", "N2"]
all i get is an error saying:
__str__ returned non-string (type list)
Like the error says, you must return a string from __str__. To do what you want you may like this :
def __str__(self):
return repr(self.wevri)
You should do:
def __str__(self):
return ' '.join(self.saxeli+self.shuasax+str(self.asaki))

String .format() only returns first character

I have a small problem with string formatting. I want to substitute {} for answers. When I change answers, Thing will correctly store the new_answer but incorrectly print it. It will somehow only print the first character!
What's going on here? I'm really confused..
class Thing(object):
def __init__(self,sentence,answer=None):
self.sentence = sentence
self.blanks = sentence.count("{}")
self.answer = (answer if answer else "___" for i in range(0,self.blanks))
def __str__(self):
return self.sentence.format(*self.answer)
def changeAnswer(self,new_answer):
self.answer = new_answer
def returnAnswer(self):
return self.answer
def test():
thang = Thing("Please put it in the {}.")
print thang # Please put it in the ___.
thang.changeAnswer("BLANK")
print thang # Please put it in the B.
print thang.returnAnswer() # BLANK
test()
You used a generator when you first initialized self.answer, but you used a string in changeAnswer. By using argument unpacking, you unpack the generator of strings into individual strings, but you end up unpacking a string into the individual characters.
Something like this should fix it (namely the changes to changeAnswer):
class Thing(object):
def __init__(self, sentence, answer=None):
self.sentence = sentence
self.num_blanks = sentence.count("{}")
self.answer = [answer or "___"] * self.num_blanks
def __str__(self):
return self.sentence.format(*self.answer)
def changeAnswer(self, new_answer):
self.answer = [new_answer] * self.num_blanks
def returnAnswer(self):
return self.answer
def test():
thang = Thing("Please put it in the {}.")
print thang # Please put it in the ___.
thang.changeAnswer("BLANK")
print thang # Please put it in the B.
print thang.returnAnswer() # BLANK
if __name__ == '__main__':
test()
Also, I would avoid methods like returnAnswer.

Categories