__class__
, ví dụ:
>>> 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>})
>>>
tương đương trong kiểu cũ-lớp:
>>> 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>
khi
>>> test.__dict__ = {'__lolcat__': "bar"}
>>> test.__lolcat__
'bar'
Có rất nhiều nhiều tên thuộc tính đặc biệt, tùy thuộc vào loại đối tượng. Ví dụ, chức năng:
>>> 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'
thấy http://docs.python.org/reference/datamodel.html cho một cái nhìn tổng quan
Tôi đã không nhận ra điều này trước đây, nhưng trực tiếp sửa đổi một '__dict__' của một lớp dường như không hoạt động với các lớp kiểu mới - kết quả trong đối tượng' TypeError: 'dict_proxy' không hỗ trợ gán mục'. Bạn vẫn có thể thấy hành vi trên trong python 3 bằng cách sửa đổi '__dict__' của cá thể, nghĩa là' test .__ dict __ ["__ class__"] = "spam" '. Ngoài ra, bạn có biết những thuộc tính khác hoạt động như thế nào không? Người duy nhất tôi tìm thấy là '__dict__'. – James
@James xem cập nhật – ch3ka
Câu hỏi của tôi là về các lớp học theo phong cách mới, những gì bạn trình bày chỉ hoạt động theo kiểu cũ. – Flavien