如何按名称访问对象的属性?

zjm*_*126 2 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!!!!'
Run Code Online (Sandbox Code Playgroud)

Jos*_*Lee 5

print b().cool
Run Code Online (Sandbox Code Playgroud)

attrs在您的__new__方法中成为对象的字典.使用.语法引用Python对象的属性.