2014-09-10 31 views
0

我已經注意到,在某些語言中,例如clojure,您可以將元數據分配給對象。python中的元數據

在Python中,你也可以做這樣的事情。

class meta_dict(dict):pass 
a={'name': "Bill", 'age':35} 
meta_a = meta_dict(a) 
meta_a.secret_meta_data='42' 
meta_a==a 
True 
secret_meta_data_dict=meta_a.__dict__ 
original_dict=dict(meta_a) 

我在想,如果這是一個合理的模式,當你需要有特定形式的數據,但需要一些其他數據優雅地跟着一起跟隨。

+0

你可能會考慮這個答案http://stackoverflow.com/a/27783928/2823755 – wwii 2015-01-05 17:43:55

回答

0

...reasonable pattern to follow...暫無評論,但這裏是另一種方式來做到這一點使用__metaclass__

>>> class MetaFoo(type): 
    def __new__(mcs, name, bases, dict): 
     dict['foo'] = 'super secret foo' 
     return type.__new__(mcs, name, bases, dict) 


>>> class Wye(list): 
    __metaclass__ = MetaFoo 


>>> class Zee(dict): 
    __metaclass__ = MetaFoo 


>>> y = Wye() 
>>> y.append(1) 
>>> y.append(2) 
>>> y 
[1, 2] 
>>> y.foo 
'super secret foo' 
>>> z = Zee({1:2, 3:4}) 
>>> z[1] 
2 
>>> z.items() 
[(1, 2), (3, 4)] 
>>> z.foo 
'super secret foo' 
>>>