How to find out the hierarchy of nested classes?

I have python code like this.

File named mymodule.py

class MyBase(object): pass 

File named data.py

 from mymodule import MyBase class A: class NestA(MyBase): pass class NestB(MyBase): pass class B: class NestA(MyBase): pass class NestB(MyBase): pass 

if I have a = A.NestA (it does not belong to the class, a is not an object of the NestA class, but the class itself), how can I find out which nested class hierarchy it belongs to? a. name gives me NestA, so this is not a problem. I want to know which external NestA class is part, that is, class A or class B. How do I do this?

+4
source share
3 answers

You can do this with the validation module:

 import inspect a = A.NestA print a in [x[1] for x in inspect.getmembers(A, inspect.isclass)] print a in [x[1] for x in inspect.getmembers(B, inspect.isclass)] 

Result:

 True False 

Addendum:

If you don't know anything about the classes in the module, you can go back and get the module.

 # for each class in a module... for klass in inspect.getmembers(inspect.getmodule(a), inspect.isclass): # see if a is in that class if a in [x[1] for x in inspect.getmembers(klass[1], inspect.isclass)]: print a, "is a member of", klass[0] 

Result:

 __main__.NestA is a member of A 
+1
source

You can do something similar with metaclass programming.

 class SetOuterClassType(type): def __init__(cls, name, bases, attrs): for attrname, attrvalue in attrs.iteritems(): if getattr(attrvalue, '__set_outerclass__', False): attrvalue.__outerclass__ = cls class OuterClassSetter(object): __metaclass__ = SetOuterClassType class MyBase(object): @classmethod def fullname(cls): if hasattr(cls,'__outerclass__'): return '%s.%s' % ( cls.__outerclass__.__name__, cls.__name__ ) else: return '%s' % cls.__name__ class A(OuterClassSetter): class NestA(MyBase): __set_outerclass__ = True class NestB(MyBase): __set_outerclass__ = True class B(OuterClassSetter): class NestA(MyBase): __set_outerclass__ = True class NestB(MyBase): __set_outerclass__ = True print A.NestA.fullname() # prints 'A.NestA' print A.NestB.fullname() # prints 'A.NestB' print B.NestA.fullname() # prints 'B.NestA' print B.NestB.fullname() # prints 'B.NestB' 
0
source

What you ask for is the result of poor design. My advise you to reconsider your decision.

0
source

All Articles