【问题标题】:how to view class variables from an inner class in python如何从python中的内部类查看类变量
【发布时间】:2013-07-16 14:44:29
【问题描述】:

我有以下具有内部类和类变量的类:

class MyForm(forms.ModelForm):

    type_constant = 'type'

    class Meta:

        model = Customer
        fields = ('type')

我想将字段变量中的“类型”替换为超类中的类型常量。如何在字段变量值中使用 type_constant?

【问题讨论】:

  • 你想写fields = MyForm.type_constant,但没有明确引用 MyForm 吗?

标签: python django visibility instance-variables class-variables


【解决方案1】:

一种方法是将外部类成员作为参数传递。据我所知,我没有更好的方法。 间类没有关于哪个类包含它的信息。并且python没有为外部类访问提供任何特定的关键字或方法。所以最好通过参数传递来实现。

__init__(self, other=None)

在课间。

【讨论】:

  • @hivert 感谢您的指出。这里我指的是外部阶级。我已经编辑了我的答案。
  • @hivert 我在这里看不到原始评论。我是不是误操作了?
  • 你修改评论后我删除了它
  • @hivert 这是你的功劳。超类提醒继承,与本上下文无关。
【解决方案2】:

您可以使用框架检查来解决它:

import inspect

def get_enclosing(name):
    # get the frame where the enclosing class in construction is evaluated
    outerframe = inspect.getouterframes(inspect.currentframe())[2][0]
    return outerframe.f_locals[name]

class Customer(object):
    pass
class MyForm(object):

    type_constant = 'type'

    class Meta:

        model = Customer
        fields = get_enclosing('type_constant')

然后:

>>> MyForm.Meta.fields
'type'

注意 1: 我正在使用 inspect 模块中记录的功能(请参阅 http://docs.python.org/2/library/inspect.html)。很可能,这仅适用于 CPython。

注意 2: 除非你真的需要一些魔法,否则参数传递可能是正确的方法。我发布了我的答案以表明它是可行的,但我不会认为它是好的代码,除非您有 strong 理由避免从外部类传递信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 2012-07-25
    • 2019-12-11
    • 1970-01-01
    • 2019-02-04
    • 2012-09-03
    相关资源
    最近更新 更多