创建了两个类,其中 Human 是 Person 的元类,想要在实例化 Person 时,通过元类 Human 将 name 和 age 属性改为 NAME、AGE,但是没有成功,不知道哪里出错了,请大神看看:
class Human(type):
def __new__(cls, name, bases, dct):
attrs = ((name, value) for name, value in dct.items() if not name.startswith('__'))
uppercase_attr = dict((name.upper(), value) for name, value in attrs)
return super(Human, cls).__new__(cls, name, bases, uppercase_attr)
class Person():
__metaclass__ = Human
country = ''
"""Person class."""
def __init__(self, name, age):
self.name = name
self.age = age
def intro(self):
"""Return an introduction."""
return "Hello, my name is %s and I'm %s." % (self.name, self.age)
运行如下:
In [23]: a = Person('dobi', 2)
In [24]: a.__dict__
Out[24]: {'age': 2, 'name': 'dobi'}
In [25]: Person.__dict__
Out[25]: mappingproxy({'country': 'gg', '__init__': <function Person.__init__ at 0x0000025E52BD9C80>, '__module__': '__main__', '__doc__': None, '__metaclass__': <class '__main__.Human'>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>})
你这样写,只对类属性有效