python - How to get all methods (including all parents' methods) of a class in its metaclass? -


for example:

class meta(type):     def __new__(cls, name, parents, attrs):         new_attrs={}         k,v in attrs.items():             # here attrs has methods defined in "name", not want.             print(k,v)             new_attrs[k] = v         return type.__new__(cls, name, parents, new_attrs)  class meta(metaclass=meta):     pass  class a(object):     def a1(self):         return self.a2()      def a2(self):         print('a2 voked')  class b(a):     def b1(self):         return self.b2()      def b2(self):         return self.a1()  class c(b):     def c1(self):         return self.b1()  class d(c,meta):     def d1(self):         return self.c1() x=d() x.d1() 

the result is:

>>>  __qualname__ meta __module__ __main__ __qualname__ d d1 <function d.d1 @ 0x0000000002a7b950> __module__ __main__ a2 voked 

as can see, in __new__ of meta, except special methods, d1 accessible. want parents' methods well(.i.e a1 a2 b1 b2 , c1 objects) can useful when class d creating via metaclass, such add decorator methods. how ?

i know 1 similar way this, little complicated , in fact, after class d created.:

import inspect  class print(object):     @classmethod     def printize(cls,):         name,attr in inspect.getmembers(cls):             # here methods accessible             # can like:             # setattr(cls,name, f(attr))  class d(c,print):     def d1(self):         return self.c1()  d.printize() 

x=d() p = type(x) while p != object:     print(p.__bases__)     p = p.__bases__[0] 

gives:

(<class '__main__.c'>, <class '__main__.meta'>) (<class '__main__.b'>,) (<class '__main__.a'>,) (<class 'object'>,) 

or can do:

import inspect print(inspect.getmro(type(x))) 

to get:

(<class '__main__.d'>, <class '__main__.c'>, <class '__main__.b'>,       <class '__main__.a'>, <class '__main__.meta'>, <class 'object'>) 

Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -