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

attrs__new__方法中成为对象的字典。Python对象的属性用.语法引用。

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

10-11 17:41