【问题标题】:__metaclass__ adding invalid attribute to class created?__metaclass__ 向创建的类添加无效属性?
【发布时间】:2014-09-29 06:56:23
【问题描述】:

元类向类添加无效属性?

这是我的代码:

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
>>> 

可以访问invalid identifier吗?

【问题讨论】:

    标签: python attributes metaclass


    【解决方案1】:

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

    getattr(Cls, 'invalid identifier')
    

    或者直接在类__dict__上映射:

    Cls.__dict__['invalid identifier']
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多