Skip to main content
 首页 » 编程设计

python之__metaclass__ 向创建的类添加无效属性

2024年10月25日10haluo1

元类 向类添加无效属性?

这是我的代码:

def __metaclass__(clsname, bases, dct): 
    dct["key1"] = "value1" 
    dct["invalid identifier"] = "value2" 
    return type(clsname, bases, dct) 
 
 
class Cls(): 
    pass 
 
 
 
for name in dir(Cls): 
    if not name.startswith("_"): 
        print name 

当我运行它时,我得到:

>>>  
invalid identifier 
key1 
>>>  

是否可以访问无效标识符?

请您参考如下方法:

您仍然可以使用 getattr() 访问该标识符:

getattr(Cls, 'invalid identifier') 

或者直接在类上__dict__映射:

Cls.__dict__['invalid identifier'] 

您不能使用直接属性访问,因为它确实不是有效标识符。