__class__
, उदाहरण के लिए:
>>> class Test(object):
__dict__ = {'__class__' : "dict of Test"}
def __init__(self):
self.__dict__['__class__'] = "dict of test"
>>> test = Test()
>>> test.__class__
<class '__main__.Test'>
>>> test.__dict__
{'__class__': 'dict of test'}
>>> Test.__dict__
dict_proxy({'__dict__': {'__class__': 'dict of test'}, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None, '__init__': <function __init__ at 0x02BD2770>})
>>>
पुरानी शैली-कक्षाओं में बराबर:
>>> class Test:
pass
>>> Test.__dict__["__class__"] = "spam"
>>> test = Test()
>>> test.__class__
<class __main__.Test at 0x02BD1110>
>>> test.__dict__ = {'__class__': "foo"}
>>> test.__class__
<class __main__.Test at 0x02BD1110>
जबकि
>>> test.__dict__ = {'__lolcat__': "bar"}
>>> test.__lolcat__
'bar'
वहाँ कई और अधिक विशेष विशेषता नाम, के आधार पर कर रहे हैं वस्तु का प्रकार। उदाहरण के लिए, कार्य:
>>> def test():pass
>>> dir(test)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
>>> test.func_closure
>>> test.__dict__['func_closure']='roflcopter'
>>> test.func_closure
>>> test.__dict__['foo']='bar'
>>> test.foo
'bar'
एक सिंहावलोकन
मुझे इससे पहले एहसास नहीं हुआ था, लेकिन कक्षा के '__dict__' को सीधे संशोधित करना नए शैली के वर्गों के साथ काम नहीं कर रहा है - इसका परिणाम' TypeError: 'dict_proxy' ऑब्जेक्ट आइटम असाइनमेंट का समर्थन नहीं करता है। उदाहरण के '__dict__' को संशोधित करके आप अभी भी उपरोक्त व्यवहार को पाइथन 3 में देख सकते हैं, यानी 'test.__ dict __ [" __ class__ "] =" स्पैम "'। साथ ही, क्या आप जानते हैं कि अन्य गुण इस तरह काम करते हैं? मुझे मिला एकमात्र दूसरा '__dict__' है। – James
@James अद्यतन देखें – ch3ka
मेरा प्रश्न नई शैली के वर्गों के बारे में था, जो आप दिखाते हैं केवल पुरानी शैली पर ही काम करता है। – Flavien