1

I have a Python class , having some variables. The definition of the class is as follows:

class student:
    def __init__(self,name,rollno,DOB,branch):
       self.name=name
       self.rollno=rollno
       self.DOB=DOB
       self.branch=branch
       self.books=[]
       self.fines=[]

I am adding new attributes for a student , and need to store the corresponding values as well (for future use). This is done using the setattr method, and works fine.

Code snippet:

setattr(student,"date_of_join",date())

Now I am approaching the problem as, if the user adds a new attribute (say, "date_of_join"), then I update a list (studattr), initially containing ["name","rollno",DOB","branch","books","fines"] to update the list of attributes. This means that the updated list will also have "date_of_join" now appended to it.

Now if I want to access this list of attributes of a student Instance, then how do I do it? ( Since the records are dynamically updated, and let us suppose I have to access x.date_of_join, then how do I join the two strings? Is there anything similar to python's os.path.join, or rather linux's system call, (merging two strings)? )

Problem:

for attribute in studattr:
    print attribute,x.attribute

{ This throws an Exception since the instance x has no variable or method named "attribute")  

PS: I tried using inspect,inspect.getmembers(x) as well as dirs(x), vars(x) ,(mentioned on stackoverflow), but it only gives me a list of variables/methods in main class body and not in init.

3
  • I guess you need getattr: getattr(x, attribute) Commented Feb 10, 2014 at 13:23
  • 2
    Instead of using an object instance on which you set attributes, isn't a normal dictionary a better fit for what you're trying to do? Commented Feb 10, 2014 at 13:24
  • 1
    If you're getting a list of variables/methods in the main class body, then you're not running dir on the instance. Commented Feb 10, 2014 at 13:26

1 Answer 1

5

Use getattr() to access dynamic attributes:

for attr in student.studattr:
    print attr, getattr(student, attr)

or use vars() will give you a dictionary of current attributes on a student:

for attr, value in vars(student).iteritems():
    print attr, value
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Worked perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.