开发者

using 'variable.xyz' format in Python

开发者 https://www.devze.com 2023-01-03 22:53 出处:网络
This is a silly question, but I can\'t figure it out so I had to ask. I\'m editing some Python code and to avoid getting too complicated, I need to be able to define a new variable along the lines of

This is a silly question, but I can't figure it out so I had to ask.

I'm editing some Python code and to avoid getting too complicated, I need to be able to define a new variable along the lines of : Car.store = False.

Variable Car has not been defined in this situation. I know I can do dicts (Car['store'] = False) etc... but it has开发者_StackOverflow中文版 to be in the format above.

Appreciate any help

Thanks.


I think the closest you can get to what you want is by adding one extra line (assuming you have defined a class called Car):

car = Car()
car.store = False

Without the first line you will get an error.

If you want brevity you could set store to False in __init__ so that only the first line is necessary.


I'm a bit late to the party, but also check out the namedtuple function in the collections module. It lets you access fields of a tuple as if they were named members of a class, and it's nice when all you want is a C-style "structure". Of course, tuples are immutable so you'd probably have to rearrange your existing code quite a bit; perhaps not the best thing for this example, but maybe keep it in mind in the future.


Maybe you can try whith this:

try:
    car.store = False
except NameError:
    #This means that car doesn't exists
    pass
except AttributeError:
    #This means that car.store doesn't exists
    pass


car, car.store = car if "car" in locals() else lambda:1, False
0

精彩评论

暂无评论...
验证码 换一张
取 消