Reputation: 126
the document says about __dict__
:
object.__dict__
A dictionary or other mapping object used to store an object’s (writable) attributes.
So my question is, how to determine if an object is a writable object, and what are the differences between writable and mutable.
Here is the code
num = 1
num.__dict__
AttributeError: int object has no attribute __dict__
class MyClass(object):
pass
myclass = MyClass()
myclass.__dict__
{}
Upvotes: 0
Views: 470
Reputation: 1945
There's no general way to determine if an object is writable.
Not every object has a __dict__
member that is writable.
Some classes use __slots__
; this limits the fields and properties of the object to those defined in the list.
Other classes override getattribute and setattribute in such a way as to prevent users from accessing those classes; this is far easier to do in C language extensions in CPython.
Overall, the easiest way to tell if class is writable is to get an instance of it and call setattr(obj, "xfoo", 1)
in a try-catch block.
Upvotes: 0
Reputation: 45542
An object whose state can change is mutable. Writing to attributes changes state. So any object that has "writable" attributes is by definition mutable.
But there can be objects whose attributes you cannot change that are still mutable. For example take threading.Lock
. You can acquire
and release
a Lock
. These methods change the state of the Lock
, but you cannot write to its attributes.
Upvotes: 1