python:确定一个类是否嵌套 [英] python: determine if a class is nested
问题描述
假设您有一个将类型作为参数的python方法;是否可以确定给定类型是否为嵌套类?
例如.在此示例中:
Suppose you have a python method that gets a type as parameter; is it possible to determine if the given type is a nested class?
E.g. in this example:
def show_type_info(t):
print t.__name__
# print outer class name (if any) ...
class SomeClass:
pass
class OuterClass:
class InnerClass:
pass
show_type_info(SomeClass)
show_type_info(OuterClass.InnerClass)
我希望对show_type_info(OuterClass.InnerClass)
的调用也能表明InnerClass是在OuterClass中定义的.
I would like the call to show_type_info(OuterClass.InnerClass)
to show also that InnerClass is defined inside OuterClass.
推荐答案
AFAIK,给定一个类,但没有其他信息,则无法确定它是否为嵌套类.但是,请参见此处有关如何使用装饰器的信息确定这一点.
AFAIK, given a class and no other information, you can't tell whether or not it's a nested class. However, see here for how you might use a decorator to determine this.
问题在于,嵌套类只是普通类,是其外部类的属性.您可能希望使用的其他解决方案可能不会-例如,inspect.getmro
仅提供基类,而不提供外部类.
The problem is that a nested class is simply a normal class that's an attribute of its outer class. Other solutions that you might expect to work probably won't -- inspect.getmro
, for example, only gives you base classes, not outer classes.
此外,很少需要嵌套类.在每种您想使用它的特定情况下,我都会强烈考虑这是否是一种好方法.
Also, nested classes are rarely needed. I would strongly reconsider whether that's a good approach in each particular case where you feel tempted to use one.
这篇关于python:确定一个类是否嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!