python - Using a metaclass to substitute a class definition? -


python 3.6

i'm trying modify behavior of third party library.

i don't want directly change source code.

considering code below:

class uselessobject(object):     pass   class pretendclassdef(object):     """     class highlight problem     """      def do_something(self):          # allot of code here          result = uselessobject()          return result 

i'd substitute own class uselessobject

i'd know if using metaclass in module intercept creation of uselessobject valid idea?

edit

this answer posted ashwini chaudhary on same question, may of use others. below answer.

p.s. discovered 'module' level __metaclass__ does't work in python 3. initial question of 'being valid idea' false

fwiw, here's code illustrates rawing's idea.

class uselessobject(object):     def __repr__(self):         return "i'm useless"  class pretendclassdef(object):     def do_something(self):         return uselessobject()  # -------  class coolobject(object):     def __repr__(self):         return "i'm cool"  uselessobject = coolobject  p = pretendclassdef() print(p.do_something()) 

output

i'm cool 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -