2010-01-19 75 views
2
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!!!!' 
+5

为防万一人不读过标题,你应该试着让它反映你的问题的其余部分。 – 2010-01-19 08:15:58

+0

打印Foo或Bar(http://en.wikipedia.org/wiki/Foobar)更酷! – ep3static 2010-01-19 09:18:21

回答

5
print b().cool 

attrs你的__new__方法变成了对象的字典。 Python对象的属性以.语法引用。

1
print "cool!!!" 

还是我错过了什么?

+0

我喜欢SO如何计票:(1 * +1)+(4 * -1)= +2 – 2010-01-19 08:24:05

+0

我笑了,你的答案 – Erik 2010-01-19 09:00:19