2010-01-19 65 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