使用虚拟类传递变量名称

使用虚拟类传递变量名称

本文介绍了Python:使用虚拟类传递变量名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是,我学到了很多东西(释义):




  • Python对象,总的来说,不知道他们的名字。

  • 不,这不可能是 * args

  • 当参数数目固定时,可以使用 locals

  • 使用全局变量()。

  • 您可能最好不要这样做,并重新思考问题。



第一点突出我对Python变量的根本误解。反应非常教育,几乎是瞬间的,显然这是一个很好理解但容易混淆的主题。



因为我想学习如何做正确的事情,创建一个虚拟类来简单地保存带有名字的变量,这被认为是不好的做法。

 类系统:pass 
S = system()
ST = 1.0
SN = 20
SL = 10

print vars(S)

这完成了我的原意,但我还在想,如果有一些我不认为可以咬我。 p>

解决方案

我这样做是对Javascript的尊敬,你在字典和实例变量之间没有任何区别。我认为它不一定是反模式,也因为不同于字典,如果你没有值,它引起AttributeError而不是KeyError,并且它更容易发现名称的错别字。正如我所说,不是反模式,前提是


  1. 该类的范围仅限于非常具体的用法

  2. 你调用的例程或方法(例如你的例子中的vars)本质上是私有的。我不想要一个带有调用语义的公共接口,也不希望它作为一个返回的实体。

  3. dummy类的名称在其意图和聚合类型它代表。

  4. 该对象的生命周期短,平静。


  5. 如果不遵守这些约束,请查看具有属性的完全识别的类。 p>

    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 (e.g. 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.

    这篇关于Python:使用虚拟类传递变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:22