Call all method python

Python: Call all methods of an object with a given set of arguments

As you see, this is giving you the names of all attributes — including plenty of special methods that are just inherited from , special data attributes such as , and , per-instance data attributes ( ), per-instance executable attributes ( ), as well as actual methods. Python objects have a unified namespace (differently from Ruby, where methods and attributes use different namespaces).

Python: Call all methods of an object with a given set of arguments

I’d like to call all methods of a python object instance with a given set of arguments, i.e. for an object like

class Test(): def a(input): print "a: " + input def b(input): print "b: " + input def c(input): print "c: " + input 

I would like to write a dynamic method allowing me to run

by iterating over all test()-methods. Thanks in advance for your help!

Not exactly sure why you want to do this. Normally in something like unittest you would provide an input on your class then reference it inside each test method.

from inspect import ismethod def call_all(obj, *args, **kwargs): for name in dir(obj): attribute = getattr(obj, name) if ismethod(attribute): attribute(*args, **kwargs) class Test(): def a(self, input): print "a: " + input def b(self, input): print "b: " + input def c(self, input): print "c: " + input call_all(Test(), 'my input') 
a: my input b: my input c: my input 

You really don’t want to do this. Python ships with two very nice testing frameworks: see the unittest and doctest modules in the documentation.

But you could try something like:

def call_everything_in(an_object, *args, **kwargs): for item in an_object.__dict__: to_call = getattr(an_object, item) if callable(to_call): to_call(*args, **kwargs) 

How to catch any method called on an object in python?, A metaclass won’t help here; although special methods are looked up on the type of the current object (so the class for instances), __getattribute__ or __getattr__ are not consulted when doing so (probably because they are themselves special methods). So to catch all dunder methods, you are forced to create them …

List all methods in COMobject

Something in the lines of :

import win32com.client ProgID = "someProgramID" com_object = win32com.client.Dispatch(ProgID) for methods in com_object: print methods 

I got the com_object.__dict__ , which lists:

[_oleobj_, _lazydata_, _olerepr_, _unicode_to_string_, _enum_, _username_, _mapCachedItems_, _builtMethods_] 
  • _oleobj_ (PyIDispatch)
  • _lazydata_ (PyITypeInfo)
  • _olerepr_ (LazyDispatchItem instance)
  • _username_ ( )

But I don’t know how to access anything on those types.

For those who find the accepted answer not working (look here for the reasons) — there’s still a way to get objects having a _prop_map_get_ attribute (a dict that holds object’s fields as keys). You just have to create the main app object with win32com.client.gencache.EnsureDispatch() .

Читайте также:  HTML Colors by Name

Here’s a convenience function I wrote that lists fields and methods of a passed COM object created that way:

from inspect import getmembers def print_members(obj, obj_name="placeholder_name"): """Print members of given COM object""" try: fields = list(obj._prop_map_get_.keys()) except AttributeError: print("Object has no attribute '_prop_map_get_'") print("Check if the initial COM object was created with" "'win32com.client.gencache.EnsureDispatch()'") raise methods = [m[0] for m in getmembers(obj) if (not m[0].startswith("_") and "clsid" not in m[0].lower())] if ****(fields) + ****(methods) > 0: print("Members of '<>' (<>):".format(obj_name, obj)) else: raise ValueError("Object has no members to print") print("\tFields:") if fields: for field in fields: print(f"\t\t") else: print("\t\tObject has no fields to print") print("\tMethods:") if methods: for method in methods: print(f"\t\t") else: print("\t\tObject has no methods to print") 

For an Excel object created with win32com.client.gencache.EnsureDispatch(«Excel.Application») its output would be:

Members of 'Excel.Application' (Microsoft Excel): Fields: ActiveCell ActiveChart ActiveDialog ActiveEncryptionSession . Workbooks WorksheetFunction Worksheets _Default Methods: ActivateMicrosoftApp AddChartAutoFormat AddCustomList Calculate . Union Volatile Wait 

Just found how to get most of the methods:

import win32com.client import pythoncom ProgID = "someProgramID" com_object = win32com.client.Dispatch(ProgID) for key in dir(com_object): method = getattr(com_object,key) if str(type(method)) == "": print key for sub_method in dir(method): if not sub_method.startswith("_") and not "clsid" in sub_method.lower(): print "\t"+sub_method else: print "\t",method 

Here’s a exemple output with ProgID = «Foobar2000.Application.0.7»

Playlists Add GetSortedTracks GetTracks Item Load Move Remove Save Name foobar2000 v1.1.13 ApplicationPath C:\Program Files (x86)\foobar2000\foobar2000.exe MediaLibrary GetSortedTracks GetTracks Rescan Minimized True Playback FormatTitle FormatTitleEx Next Pause Previous Random Seek SeekRelative Start Stop ProfilePath file://C:\Users\user\AppData\Roaming\foobar2000 

To list the attributes of an object you can use the dir() function. This is a built in function of python and does not need to be imported.Try something like:

To see the attributes of the object.

List of methods for python shell?, If you want only methods, then. def methods (obj): return [attr for attr in dir (obj) if callable (getattr (obj, attr))] But do try out IPython, it has tab completion for object attributes, so typing obj. shows you a list of available attributes on that object. Share. answered Sep 4, 2009 at 12:44.

How to alias all methods from an object?

I’m creating a script that’s actually an environment for other users to write code on.

I’ve declared several methods in a class and instantiate an object so users can use those methods as simple interpreter functions, like so:

from code import interact class framework: def method1(self, arg1): # code for method1 def method2(self, arg2): # code for method2 def main(): fw = framework() # Aliases method1 = fw.method1 method2 = fw.method2 interact(local=locals()) 

Since I don’t want the user to call the methods with fw.method1(arg) , I setup aliases. The problem is, since the framework class is under development, I have to keep updating the main script with new aliases for the methods I create.

Читайте также:  How to do hashing in java

Is there a simple way of getting rid of the » fw. » part on the calls and have all the methods under class framework automatically visible under main?

You control the dictionary passed to interact , so put what you want in it without worrying with local variables in main :

d=<> for n in vars(framework): if n.startswith('_'): continue # probably x=getattr(fw,n) if callable(x): d[n]=x interact(local=d) 

This works for regular, static, and class methods. It doesn’t see instance attributes (unless they’re shadowing a class attribute ) or inherited methods.

The former matters only if the instance stores functions as attributes (in which case you might or might not want them available). The latter is convenient in that it omits object ; if there are other base classes, they can easily be included by searching framework.__mro__ (and still omitting object ).

I don’t know what you plan to do with the functions, but if they are not static it will not likely work outside of the class:

fs = [func for func in dir(c) if callable(getattr(c, func)) and not func.startswith("__")] for func in fs: globals()[func] = getattr(c, func) 

This will put all custom functions within the class c to global scope.

You basically want to do two things:

  1. get a list of methods of a class instance
  2. dynamically add functions to your local scope

The former can be achieved with the inspect module from the standard library, the latter by using vars .

import inspect from code import interact class framework: def method1(self, arg1): # code for method1 def method2(self, arg2): # code for method2 def main(): fw = framework() # get the methods of fw and update vars(). # getmembers returns a list of two-tuples with (, ) methods = inspect.getmembers(fw, predicate=inspect.ismethod) vars().update() interact(local=locals()) 

Here’s something similar to @Davis Herring’s answer, fleshed-out and repackaged:

#from code import interact def interact(local): local['method1'](42) local['method2']('foobar') class Framework: def method1(self, arg1): print('Framework.method1() called'.format(arg1)) def method2(self, arg2): print('Framework.method2() called'.format(arg2)) def get_callables(obj): return def main(): fw = Framework() # # Aliases # method1 = fw.method1 # method2 = fw.method2 interact(local=get_callables(fw)) if __name__ == '__main__': main() 
Framework.method1(42) called Framework.method2('foobar') called 

Get all object attributes in Python?, 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 …

Читайте также:  Demo

List of methods for python shell?

You’d have already found out by my usage of terminology that I’m a python n00b.

straight forward question:

How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a ‘.methods’ after the object)?

Existing answers do a good job of showing you how to get the ATTRIBUTES of an object, but do not precisely answer the question you posed — how to get the METHODS of an object. Python objects have a unified namespace (differently from Ruby, where methods and attributes use different namespaces). Consider for example:

>>> class X(object): . @classmethod . def clame(cls): pass . @staticmethod . def stame(): pass . def ****(self): pass . def __init__(self): . self.lam = lambda: None . self.val = 23 . >>> ****() >>> dir(x) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'clame', 'lam', 'meth', 'stame', 'val'] 

((output split for readability)).

As you see, this is giving you the names of all attributes — including plenty of special methods that are just inherited from object , special data attributes such as __class__ , __dict__ and __doc__ , per-instance data attributes ( val ), per-instance executable attributes ( lam ), as well as actual methods.

If and when you need to be more selective, try:

>>> import inspect >>> [n for n, v in inspect.getmembers(x, inspect.ismethod)] ['__init__', 'clame', 'meth'] 

Standard library module inspect is the best way to do introspection in Python: it builds on top of the built-in introspection hooks (such as dir and more advanced ones) to offer you useful, rich, and simple introspection services . Here, for example, you see that only instance and class methods specifically designed by this class are shown — not static methods, not instance attributes whether callable or not, not special methods inherited from object . If your selectivity needs are slightly different, it’s easy to build your own tweaked version of ismethod and pass it as the second argument of getmembers , to tailor the results to your precise, exact needs.

will list off all the methods you can call for an integer.

Its simple do this for any object you have created

it will return a list of all the attributes of the object.

List methods in Python, Python List Methodshas multiple methods to work with Python lists, Below we’ve explained all the methods you can use with Python lists, for example, append(), copy(), Removes a given object from the List. 10: reverse() Reverses objects of the List in place. 11: sort() Sort a List in ascending, descending, or …

Источник

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