OiO.lk Blog python Changing instance's attribute name via metaclass
python

Changing instance's attribute name via metaclass


I’m to do a metaclass that should add a prefix ‘custom_’ to all the properties and methods of my class CustomClass except for magic methods.
Here is the code:

class CustomClass(metaclass=CustomMeta):
    x = 50

    def __init__(self, val=99):
        self.val = val

    def line(self):
        return 100

    def __str__(self):
        return "Custom_by_metaclass"

I wrote a following metaclass that works fine for this case, but I faced a problem that I can’t change instance’s argument self.val to self.custom_val so that my assertions fails:

inst = CustomClass()
assert inst.custom_val == 99 #Fails

Anyway, others assertions go fine:

assert CustomClass.custom_x == 50
inst = CustomClass()
assert inst.custom_x == 50
assert inst.custom_line() == 100
assert str(inst) == "Custom_by_metaclass"

Here is my metaclass:

class CustomMeta(type):

    def __new__(cls, name_class, base, attrs):
        custom_attrs = {}
        for key, value in attrs.items():
            if not key.startswith('__') and not key.endswith('__'):
                custom_attrs['custom_' + key] = attrs[key]
            else:
                custom_attrs[key] = attrs[key]
        return type.__new__(cls, name_class, base, custom_attrs)

What should I do to manage my problem?



You need to sign in to view this answers

Exit mobile version