python - 如何通过名称访问对象的属性?

标签 python

class a(type):
    def __str__(self):
        return 'aaa'
    def __new__(cls, name, bases, attrs):
        attrs['cool']='cool!!!!'
        new_class = super(a,cls).__new__(cls, name, bases, attrs)
                #if 'media' not in attrs:
                    #new_class.media ='media'
        return new_class

class b(object):
    __metaclass__=a
    def __str__(self):
        return 'bbb'

print b
print b()['cool']#how can i print 'cool!!!!'

最佳答案

print b().cool
__new__ 方法中的

attrs 成为对象的字典。 Python 对象的属性通过 . 语法引用。

关于python - 如何通过名称访问对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2092002/

相关文章:

python - 为什么 Python 中的 @foo.setter 对我不起作用?

python - 将 .RData 文件加载到 Python 中

python - 连接到 DataFrame 将给出两个单独的起始索引

python - 我该如何修复 : 'int' object is not iterable

python - 光学字符识别多行检测

python - 在 Python 中传递隐式参数?

python - 引号中的 mypy 显式类型提示仍然给出未定义的错误

python - 计算 pandas 数据帧行对中的匹配数

python - python 中缺失值的统计

python - 将 build_ext 选项传递给 pip install