简体   繁体   中英

Python: Using a dummy class to pass variable names?

This is a followup to function that returns a dict whose keys are the names of the input arguments , which I learned many things (paraphrased):

  • Python objects, on the whole, don't know their names.
  • No, this is not possible in general with *args . You'll have to use keyword arguments
  • When the number of arguments is fixed, you can do this with locals
  • Using globals(). This will only work if the values are unique in the module scope, so it's fragile
  • You're probably better off not doing this anyway and rethinking the problem.

The first point highlighting my fundamental misunderstanding of Python variables. The responses were very pedagogic and nearly instantaneous, clearly this is both a well-understood yet easily confused topic.

Since I'd like to learn how to do things proper, is it considered bad practice to create a dummy class to simply hold the variables with names attached to them?

class system: pass
S = system ()
S.T = 1.0
S.N = 20
S.L = 10

print vars(S)

This accomplishes my original intent, but I'm left wondering if there is something I'm not considering that can bite me later.

I do it as a homage to Javascript, where you don't have any distinction between dictionaries and instance variables. I think it's not necessarily an antipattern, also because differently from dictionaries, if you don't have the value it raises AttributeError instead of KeyError, and it is easier to spot typos of the name. As I said, not an antipattern, provided that

  1. the scope of the class is restricted to a very specific usage
  2. the routine or method you are calling (eg vars in your example) is private in nature. I would not want a public interface with that calling semantics, nor I want it as a returned entity
  3. the name of the "dummy" class is extremely clear in its intent and the kind of aggregate it represents.
  4. the lifetime of that object is short and uneventful. It is just a temporary bag of data.

If these constraints are not respected, go for a fully recognized class with properties.

you can do that, but why not use a dictionary?

but if you do that, you're better off passing keywords args to the class's constructor, and then let the constructor copy them to the app's members. something like:

class Foo(object):

    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM