• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

python: question about instances

foges

Senior member
I want to create an instance with a name that is dependent upon user input. So i have a string of user input in string 'x' now i want to make this an instance, but if i do this the normal way:

x = klass()

'x' will just become the name of the instance, not the sring that x represents. how would i go about doing this?
 
why do you want to do this?

Why not put a string instance variable inside the class and have a getName() method?

class klass:
name = ""
def __init__(self,name):
name = self.name

def getName(self):
return name



>>> x = klass("myName")
>>> print x.getName()
'myName'
 
Thanks for the reply, im still a newb a python.

Anyways, for practice im trying to create a program that stores informations about students at an imaginary school. So i have made a class with functions such as "add student", "add subject to student", "give grade to student for subject", "view credentials". I know its a prety basic program, but if im going to have a variable number of students then i have to have a variable number of instances, or not?
 
If you have a variable number of students, then yes you should have a variable number of student objects (instances).

You can store student objects in a list (or a set if you want to ensure uniqueness). Lists and sets will dynamically resize themselves, so they will always be able to hold more student objects.

http://docs.python.org/tut/node7.html

example:

I'm assuming here that you have a text file for input called "student.txt" and that every line of the file has the name of 1 student.

reader = open("student.txt",'r') #open a file reader
studentList = []

while True:
line = reader.readline()

#note that '' is 2 single quotes, not one double quote
if line == '': #readers return an empty string when there are no lines left to read
break

line = line[:-1] #strip the trailing end of line character

myStudent = Student(line) #create a student from the name
studentList.append(myStudent) #add the student to the list

print studentList
 
Thanks, yeah i think i got it to work with lists now 🙂

EDIT: On a different topic: what is the easiest way / what do i need to learn to get python to interact with a website (eg. get information from a table on a website or sign me in to a website)?
 
Back
Top