Add method to class dynamically using decorator

I would add a method to classdynamically ... the function name will also be passed dynamically.

How can i do this? I tried this way

def decor(*var):
  def onDecorator(aClass):
    class onInstance:
        def __init__(self,*args,**kargs):
            setter=var
            aClass.setter = self.flam
            self.wrapped = aClass(*args,**kargs)

        def __getattr__(self,attr):
            return getattr(self.wrapped,attr)

        def __setattr__(self,attr,value):
            if attr == 'wrapped':
                self.__dict__[attr]=value
            else:
                setattr(self.wrapped,attr,value)

        def flam(self,*args):
            self.__setattr__('dimension',len(args[0]))

    return onInstance
return onDecorator

but if I do this:

print(aClass.__dict__)

I have

'setter': <bound method onInstance.flam of <__main__.onInstance object at 0x522270>>

instead var: .....

I have this class:

class D:
  def __init__(self, data):
    self.data = data
    self.dimension = len(self.data)

I would call:

D.name()

and back self.dimension, but I don’t know namein advance

+6
source share
3 answers

This is my decorator.

def decorator(name):
    def wrapper(K):
        setattr(K, name, eval(name))
        return K
    return wrapper

This is an example method.

def myfunc(self):
    print "Istance class: ", self

This is a decorated class.

@decorator("myfunc")
class Klass:
    pass

I hope this is useful and what you need :)

+13
source
def dec(cls):
    setattr(cls, 'c', 0)    # add atr counter to CLS

    def __init__(self):
        cls.c += 1  # +1 to CLS, not self!

    def get_c(self=None):
        return cls.c    # get current value from CLS


    setattr(cls, '__init__', __init__)  # add new __init__ IT WILL OVERWRITE original __init__
    setattr(cls, 'get_c', get_c)    # add new method
    return cls

@dec
class A:
    pass

print(A.c) # 0
user, _, _ = A(), A(), A()
user.get_c()  # 3

if you want to keep the original init and add a new value to def init

def __init__(self):
    cls.c += 1  # +1 to CLS, not self!
    cls.__init__
0
source

Here's a simplified py3 solution

class A(object):
    def a(self):
        print('a')

def add_b(cls):
    def b(self):
        print('b')

    setattr(cls, 'b', b)
    return cls

@add_b
class C(A):
    pass

C().b() # 'b'
0
source

All Articles