Question

I have the following in a Python script:

setattr(stringRESULTS, "b", b)

Which gives me the following error:

AttributeError: 'str' object has no attribute 'b'

Can any-one telling me what the problem is here?

Était-ce utile?

La solution

Don't do this. To quote the inestimable Greg Hewgill,

"If you ever find yourself using quoted names to refer to variables, there's usually a better way to do whatever you're trying to do."

[Here you're one level up and using a string variable for the name, but it's the same underlying issue.] Or as S. Lott followed up with in the same thread:

"90% of the time, you should be using a dictionary. The other 10% of the time, you need to stop what you're doing entirely."

If you're using the contents of stringRESULTS as a pointer to some object fred which you want to setattr, then these objects you want to target must already exist somewhere, and a dictionary is the natural data structure to store them. In fact, depending on your use case, you might be able to use dictionary key/value pairs instead of attributes in the first place.

IOW, my version of what (I'm guessing) you're trying to do would probably look like

d[stringRESULTS].b = b

or

d[stringRESULTS]["b"] = b

depending on whether I wanted/needed to work with an object instance or a dictionary would suffice.

(P.S. relatively few people subscribe to the python-3.x tag. You'll usually get more attention by adding the bare 'python' tag as well.)

Autres conseils

Since str is a low-level primitive type, you can't really set any arbitrary attribute on it. You probably need either a dict or a subclass of str:

class StringResult(str):
    pass

which should behave as you expect:

my_string_result = StringResult("spam_and_eggs")
my_string_result.b = b

EDIT:

If you're trying to do what DSM suggests, ie. modify a property on a variable that has the same name as the value of the stringRESULTS variable then this should do the trick:

locals()[stringRESULTS].b = b

Please note that this is an extremely dangerous operation and can wreak all kinds of havoc on your app if you aren't careful.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top