So I have a class with the following method:
def Add(self,new_name):
self.new_name=....
I want to add an attribute with the title "new_name" that will be passed from somewhere else. Obviously, in the above program I simply created an attribute with the string "new_name" instead of the actual argument input.
How should I go about making sure the attribute's name is the actual parameter? I believe in C++ it's easy to use c_str()
here, but with Python I'm not sure.
ex. Add('hello')
should create a new attribute self.hello
which I can then store with information. Thank you.
EDIT: Ok I see I should use setattr() now. However, I seem to not be getting the expected results. Is this how I would use it where the initialization is a list comprehension? I tried the two ways and neither worked as shown below:
def Add(self,new_name): #also doesn't work
setattr(self, new_name,[API(self.var1,str(new_name),i) for i
in range(self._NumRows)])
def Add(self,new_name): #also doesn't work
setattr(self, new_name,[])
self.new_name=[API(self.var1,str(new_name),i) for i
in range(self._NumRows)])
where API takes 3 arguments (I know this isn't the problem because this works fine as long as I don't use setattr() and the name is already known so it's nothing with the API.
EDIT: For those suggesting dictionary, I'm not storing data with these attributes. I'm creating a method which creates a new attribute for users who are creating derived classes of my base class. It's to abstract away the creation of additional attributes because I was told my code would likely be adopted in the future when I leave (I'm an intern) and to make it as easy as possible to create derived classes.
EDIT: Nevermind, I mislabeled a variable. It works! Thank you.