Answer the question
In order to leave comments, you need to log in
How to use a value from a tuple as an attribute?
I have a class with many attributes, and I need to add the value of each of them to the dictionary, after which the dictionary needs to be written to a json file. Since there are many attributes, I decided to write the names of the attributes into a tuple and use the for loop, but when I try to substitute my variable as an attribute, an error is thrown, please help, I will be very grateful.
Answer the question
In order to leave comments, you need to log in
class emp:
name='Harsh'
salary='25000'
def show(self):
print (self.name)
print (self.salary)
e1 = emp()
# Use getattr instead of e1.name
print (getattr(e1,'name'))
# returns true if object has attribute
print (hasattr(e1,'name'))
# sets an attribute
setattr(e1,'height',152)
# returns the value of attribute name height
print (getattr(e1,'height'))
# delete the attribute
delattr(emp,'salary')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question