i have a little problem when i try to attach a class to an object in python. I have a textfile ‘file’, which is seperated into a list for each line. The program will read every line and print a name and a longname. Imagine that the textfile look like this:
“John ‘\n’ John Travolta” (…)
Here’s my bit of code:
class Name:
def __init__(self, name, longname):
self.name=name
self.longname=longname
def __str__(self):
s="Name:"+self.name
s+="\n Longname:"+self.longname
def func():
for line in file:
name=line[:1]
longname=line['\n':]
c=Name(name, longname)
c.func()
I get the error message that my ‘name’ and ‘longname’ is not defined but I did this with my function??? 🙁
It works if I put the function outside the class, like this:
def func():
for line in file:
name=line[:1]
longname=line['\n':]
c=Name(name, longname)
print c
Need help!
You need to assign something to name and longname before you can use them:
No.
namethere is different from the globalname.I don’t think it makes any sense to move your
funcmethod inside the class definition. The code that you said works is a better way to do it.