Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.
To print the attributes of an object we can use “object. __dict__” and it return a dictionary of all names and attributes of object. After writing the above code (python print object attributes), once you will print “x. __dict__” then the output will appear.
Use Python's vars() to Print an Object's Attributes The dir() function, as shown above, prints all of the attributes of a Python object.
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.
For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr
built-in function. As the user can reimplement __getattr__
, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir
function returns the keys in the __dict__
attribute, i.e. all the attributes accessible if the __getattr__
method is not reimplemented.
For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect
module determine the class methods, methods or functions.
That is why the new __dir__()
method has been added in python 2.6
see:
Here is a practical addition to the answers of PierreBdR and Moe:
dir()
seems to be enough.For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir()
, look for __class__
, and then to go for its __bases__
:
# code borrowed from the rlcompleter module
# tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' )
# or: from rlcompleter import get_class_members
def get_class_members(klass):
ret = dir(klass)
if hasattr(klass,'__bases__'):
for base in klass.__bases__:
ret = ret + get_class_members(base)
return ret
def uniq( seq ):
""" the 'set()' way ( use dict when there's no set ) """
return list(set(seq))
def get_object_attrs( obj ):
# code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )
ret = dir( obj )
## if "__builtins__" in ret:
## ret.remove("__builtins__")
if hasattr( obj, '__class__'):
ret.append('__class__')
ret.extend( get_class_members(obj.__class__) )
ret = uniq( ret )
return ret
(Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for get_object_attrs()
as for dir()
, and for old-style classes the main addition to the dir()
output seem to be the __class__
attribute.)
Only to supplement:
dir()
is the most powerful/fundamental tool. (Most recommended)Solutions other than dir()
merely provide their way of dealing the output of dir()
.
Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __
, but sometimes you may well need the __doc__
doc-string.
__dir__()
and dir()
returns identical content.__dict__
and dir()
are different. __dict__
returns incomplete content.IMPORTANT: __dir__()
can be sometimes overwritten with a function, value or type, by the author for whatever purpose.
Here is an example:
\\...\\torchfun.py in traverse(self, mod, search_attributes)
445 if prefix in traversed_mod_names:
446 continue
447 names = dir(m)
448 for name in names:
449 obj = getattr(m,name)
TypeError: descriptor __dir__
of 'object'
object needs an argument
The author of PyTorch modified the __dir__()
method to something that requires an argument. This modification makes dir()
fail.
If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.
This is how I do it, useful for simple custom objects to which you keep adding attributes:
Given an object created with obj = type("Obj",(object,),{})
, or by simply:
class Obj: pass
obj = Obj()
Add some attributes:
obj.name = 'gary'
obj.age = 32
then, to obtain a dictionary with only the custom attributes:
{key: value for key, value in obj.__dict__.items() if not key.startswith("__")}
# {'name': 'gary', 'age': 32}
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