S
S
Sairos2021-05-06 22:51:24
Python
Sairos, 2021-05-06 22:51:24

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.

60944888a0b39051351539.png

60944892b8160344769950.png

60944899d18bf909410845.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexa2007, 2021-05-06
@Alexa2007

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')

M
MinTnt, 2021-05-07
@MinTnt

First, you don't have a record of what value self.i has, so you still need to declare

for i in hw:
    self.i = i
    ....self.i.text()

Second, why apply self to a temporary variable that only exists in the loop. Will it need to be used somewhere else in the code?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question