我是python元类的新手并运行以下代码:
class A(type):
@classmethod
def _handle_attrs(cls, class_name, bases, attrs, **kwargs):
# Now lets find all handlers defined for this class
current_attr = [(att, getattr(attrs[att], "__my_attr")) for att in attrs if
hasattr(attrs[att], '__my_attr')]
print hasattr(attrs, '__my_attr') # returns False
def __new__(cls, class_name, bases, attrs, **kwargs):
cls._handle_attrs(class_name, bases, attrs, **kwargs)
return type.__new__(cls, class_name, bases, attrs, **kwargs)
# adding the decorators args as a class attribute
def my_decorator(*args, **kwargs):
def _my_decorator(cls):
if hasattr(cls, '__my_attr'):
cls.__my_attr.update(kwargs)
else:
cls.__my_attr = kwargs
return cls
return _my_decorator
class B:
__metaclass__ = A
def get_attr_dict(self):
return getattr(self, '__my_attr', None)
@my_decorator(w = 'W')
@my_decorator(z = 'Z')
class C(B):
x = 'X'
y = 'Y'
test = C()
print test.__class__.__dict__
print test.__my_attr # this returns {'w': 'W', 'z': 'Z'}
我通过使用类装饰器 - my_decorator将类属性添加到C类。 在_handle_attrs函数中,我想对添加的属性做一些事情。
问题是添加的属性添加在:test._ _class __._ _dict__下,当在元类中创建C时,我不知道如何访问它们......
答案 0 :(得分:2)
元类' __new__
运行在使用它的类的定义上。由于
@my_decorator(w = 'W', z = 'Z')
class C(B):
x = 'X'
y = 'Y'
相当于
class C(B):
x = 'X'
y = 'Y'
C = my_decorator(w = 'W', z = 'Z')(C)
很明显,当装饰者添加属性时,元类已经完成了它的工作。