如何在python中从内部类查看类变量

如何在python中从内部类查看类变量,python,django,visibility,instance-variables,class-variables,Python,Django,Visibility,Instance Variables,Class Variables,我有以下带有内部类和类变量的类: class MyForm(forms.ModelForm): type_constant = 'type' class Meta: model = Customer fields = ('type') 我想将fields变量中的“type”替换为super类中的type常量。如何在字段变量值中使用type_常量?一种方法是将外部类成员作为参数传递。据我所知,没有更好的办法了。 类间没有关于包含它的类的信息。

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

class MyForm(forms.ModelForm):

    type_constant = 'type'

    class Meta:

        model = Customer
        fields = ('type')

我想将fields变量中的“type”替换为super类中的type常量。如何在字段变量值中使用type_常量?

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

__init__(self, other=None)

在类间。

您可以使用框架检查来解决此问题:

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')
然后:

注1:我正在使用
检查
模块中记录的功能(请参阅)。很可能,这只适用于CPython


注意2:除非您真的需要一些魔法,否则参数传递可能是正确的方法。我发布了我的答案来证明它是可行的,但是我不认为它是好代码,除非你有一个强的强的<强>理由避免从外部类传递信息。< /P>你想写<代码>字段= MyFrase.Type常数[/Cord]?但是没有明确地引用MyFrm?@ Hivit谢谢你指出。这里我指的是外舱。我已经编辑了我的答案。@hivert我在这里看不到原始评论。我操作不当了吗?在你修好你的电脑后我把它删除了comment@hivert这是你的信用卡。超类提醒继承,这与此上下文无关。
>>> MyForm.Meta.fields
'type'