Suppose o
is a Python object, and I want all of the fields of o
, without any methods or __stuff__
. How can this be done?
I've tried things like:
[f for f in dir(o) if not callable(f)] [f for f in dir(o) if not inspect.ismethod(f)]
but these return the same as dir(o)
, presumably because dir
gives a list of strings. Also, things like __class__
would be returned here, even if I get this to work.
To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class.
__slots__ is a class variable. If you have more than one instance of your class, any change made to __slots__ will show up in every instance. You cannot access the memory allocated by the __slots__ declaration by using subscription. You will get only what is currently stored in the list.
The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__.
You can get it via the __dict__
attribute, or the built-in vars
function, which is just a shortcut:
>>> class A(object): ... foobar = 42 ... def __init__(self): ... self.foo = 'baz' ... self.bar = 3 ... def method(self, arg): ... return True ... >>> a = A() >>> a.__dict__ {'foo': 'baz', 'bar': 3} >>> vars(a) {'foo': 'baz', 'bar': 3}
There's only attributes of the object. Methods and class attributes aren't present.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With