Python get method attributes

Get all object attributes in Python? [duplicate]

Is there a way to get all attributes/methods/fields/etc. of an object in Python? vars() is close to what I want, but it doesn’t work unless an object has a __dict__ , which isn’t always true (e.g. it’s not true for a list , a dict , etc.).

4 Answers 4

note that the behavior of dir() is often manipulated to show interesting attributes, rather than strictly all; for instance it doesn’t show attributes inherited through a metaclass, or it may be overridden with a __dir__ method.

class MyObj(object): def __init__(self): self.name = 'Chuck Norris' self.phone = '+6661' obj = MyObj() print(obj.__dict__) print(dir(obj)) # Output: # obj.__dict__ --> # # dir(obj) --> ['__class__', '__delattr__', '__dict__', '__doc__', # '__format__', '__getattribute__', '__hash__', # '__init__', '__module__', '__new__', '__reduce__', # '__reduce_ex__', '__repr__', '__setattr__', # '__sizeof__', '__str__', '__subclasshook__', # '__weakref__', 'name', 'phone'] 

The OP specifically mentions that he is interested in cases where there is no __dict__ — otherwise he could use vars

vars() is close to what I want, but it doesn’t work unless an object has a dict, which isn’t always true (e.g. it’s not true for a list, a dict, etc.). he clearly said that is NOT what he wants

What you probably want is dir() .

The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__ , may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__ : many of these objects may have so many dynamic attrs it doesn’t won’t actually know what it has until you try to access it.

Читайте также:  Java layout one column

In the short run, if dir() isn’t sufficient, you could write a function which traverses __dict__ for an object, then __dict__ for all the classes in obj.__class__.__mro__ ; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions — if it looks like a duck, cross your fingers, and hope it has .feathers .

Not sure if this is what you’re looking for, but. attrs = dir(obj) will store the array of attributes as strings in attrs . Then to access them, you can always use getattr(obj, attrs[i]) to get the i th attribute in the attrs array.

Источник

how python display list of all attribute and method using dir(object)?

And it does print len of the object and further inspecting I also found len dunder method is available in otherclass object using dir I am wondering how python display the value for dir(object) as there is no dir dunder method in the result of dir(otherclass)

3 Answers 3

I mean for me (python 3.6) dir(otherclass) prints

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] 

The iteresting one is __dict__ .

otherclass.__dict__ == \ mappingproxy(, '__doc__': None, '__len__': , '__module__': '__main__', '__weakref__': >) 

So this holds all the methods/attributes specific to that object. However, where do all the others come from? Well, from the superclass:

object.__dict__ == \ mappingproxy(, '__delattr__': , '__dir__': , '__doc__': 'The most base type', '__eq__': , '__format__': , '__ge__': , '__getattribute__': , '__gt__': , '__hash__': , '__init__': , '__init_subclass__': , '__le__': , '__lt__': , '__ne__': , '__new__': , '__reduce__': , '__reduce_ex__': , '__repr__': , '__setattr__': , '__sizeof__': , '__str__': , '__subclasshook__': >) 

So dir looks for a __dir__ method, then looks at __dict__ (or __slots__ ) and then recursively looks up the method resolution order (available as otherclass.mro() ) at each class in turn.

Источник

Is there a function in Python to list the attributes and methods of a particular object?

Is there a function in Python to list the attributes and methods of a particular object? Something like:

ShowAttributes ( myObject ) -> .count -> .size ShowMethods ( myObject ) -> len -> parse 

property is a name given to a different concept in python. the term attribute would suit you better. an in-depth reading that I like, about both is cafepy.com/article/python_attributes_and_methods/…

5 Answers 5

You want to look at the dir() function:

>>> li = [] >>> dir(li) ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] 

li is a list, so dir(li) returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves.

Edit in response to comment:

No this will show all inherited methods as well. Consider this example:

class Foo: def foo(): pass class Bar(Foo): def bar(): pass 

Python interpreter:

>>> from test import Foo, Bar >>> dir(Foo) ['__doc__', '__module__', 'foo'] >>> dir(Bar) ['__doc__', '__module__', 'bar', 'foo'] 

You should note that Python’s documentation states:

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

Therefore it’s not safe to use in your code. Use vars() instead. Vars() doesn’t include information about the superclasses, you’d have to collect them yourself.

If you’re using dir() to find information in an interactive interpreter, consider the use of help() .

Источник

Оцените статью