元类不改变属性

时间:2017-11-11 12:13:15

标签: python python-2.7 metaclass

为什么以下元类没有将所有属性转换为大写?相反,它似乎什么都不做。

class UpperAttrMetaclass(type):

    def __new__(cls, clsname, bases, dct):

        uppercase_attr = {}
        for name, val in dct.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        return super(UpperAttrMetaclass, cls).__new__(cls, clsname, bases, uppercase_attr)


class MyKlass(object):
    __metaclass__ = UpperAttrMetaclass

    def __init__(self):
        print ("Instantiating the object in the __init__ of the class")

    def foo(self, param):
        pass

    some_attribute = 2

print("")
print ("--------------------------------------")
print ("This is the first line of the program")
print ("--------------------------------------")
m = MyKlass()
print(m)
print(m.__dict__)

1 个答案:

答案 0 :(得分:0)

因此,从注释中,如果要将所有实例属性直接设置为大写,则可以在类本身上简单地实现__setattr__。 (并且可能__getattr__以便规范化所有属性访问)

class UpperAttrMetaclass(type):

    def __new__(cls, clsname, bases, dct):

        uppercase_attr = {}
        for name, val in dct.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        return super(UpperAttrMetaclass, cls).__new__(cls, clsname, bases, uppercase_attr)

   def __setattr__(cls, attr, value):
      if not attr.startswith("__"):
          attr  = attr.upper()
      super(UpperAttrMetaclass, cls).__setattr__(attr, value)

class MyKlass(object):
    __metaclass__ = UpperAttrMetaclass

    def __init__(self):
        print ("Instantiating the object in the __init__ of the class")

    def foo(self, param):
        pass

    def __setattr__(self, attr, value):
         super(MyKlass, self).__setattr_(attr.upper(), value)

    some_attribute = 2

同样在元类上使用__setattr__,确保创建类后的类属性et也转换为大写。对于普通实例属性,只需要类中的__setattr__