How do I get list of methods in a Python class?Finding what methods a Python object hasHow do I look inside a Python object?How to get a complete list of object's methods and attributes?How to enumerate an object's properties in Python?Can a Python decorator of an instance method access the class?How to decorate all functions of a class without typing it over and over for each method?How can I list the methods in a Python 2.5 module?How Do I Perform Introspection on an Object in Python 2.x?Run all functions in classHow to dynamically create module level functions from methods in a classHow do I check if a list is empty?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonDoes Python have a ternary conditional operator?Getting the class name of an instance?Proper way to declare custom exceptions in modern Python?How do I list all files of a directory?Does Python have a string 'contains' substring method?
What do you call a Matrix-like slowdown and camera movement effect?
How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?
Do I have a twin with permutated remainders?
"You are your self first supporter", a more proper way to say it
What defenses are there against being summoned by the Gate spell?
Minkowski space
Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)
How to write a macro that is braces sensitive?
What do the dots in this tr command do: tr .............A-Z A-ZA-Z <<< "JVPQBOV" (with 13 dots)
How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?
Is this a crack on the carbon frame?
Can a Warlock become Neutral Good?
Arthur Somervell: 1000 Exercises - Meaning of this notation
Is it legal for company to use my work email to pretend I still work there?
How can bays and straits be determined in a procedurally generated map?
What are these boxed doors outside store fronts in New York?
How does strength of boric acid solution increase in presence of salicylic acid?
Mage Armor with Defense fighting style (for Adventurers League bladeslinger)
What's the output of a record cartridge playing an out-of-speed record
To string or not to string
In Japanese, what’s the difference between “Tonari ni” (となりに) and “Tsugi” (つぎ)? When would you use one over the other?
Mathematical cryptic clues
What typically incentivizes a professor to change jobs to a lower ranking university?
What are the differences between the usage of 'it' and 'they'?
How do I get list of methods in a Python class?
Finding what methods a Python object hasHow do I look inside a Python object?How to get a complete list of object's methods and attributes?How to enumerate an object's properties in Python?Can a Python decorator of an instance method access the class?How to decorate all functions of a class without typing it over and over for each method?How can I list the methods in a Python 2.5 module?How Do I Perform Introspection on an Object in Python 2.x?Run all functions in classHow to dynamically create module level functions from methods in a classHow do I check if a list is empty?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonDoes Python have a ternary conditional operator?Getting the class name of an instance?Proper way to declare custom exceptions in modern Python?How do I list all files of a directory?Does Python have a string 'contains' substring method?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?
Also see:
How can I list the methods in a
Python 2.5 module?
Looping over
a Python / IronPython Object
Methods
Finding the methods an
object has
How do I look inside
a Python object?
How Do I
Perform Introspection on an Object in
Python 2.x?
How to get a
complete list of object’s methods and
attributes?- Finding out which
functions are available from a class
instance in python?
python
add a comment |
I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?
Also see:
How can I list the methods in a
Python 2.5 module?
Looping over
a Python / IronPython Object
Methods
Finding the methods an
object has
How do I look inside
a Python object?
How Do I
Perform Introspection on an Object in
Python 2.x?
How to get a
complete list of object’s methods and
attributes?- Finding out which
functions are available from a class
instance in python?
python
43
@S.Lott Why can't you use the Force? What's wrong with the Force?
– jononomo
Jan 4 '13 at 0:51
1
The source..... the source...
– RickyA
Oct 9 '13 at 15:25
3
@JonCrowell that's not how the Force works.
– Ken Williams
Apr 24 '17 at 3:24
For Cython using the compiler directivebinding
works: stackoverflow.com/a/46041480/1959808
– Ioannis Filippidis
Sep 9 '17 at 7:46
On python3:[f for f in dir(ClassName) if not f.startswith('_')]
or justdir(ClassName)
for everything
– Seraf
Feb 7 at 16:23
add a comment |
I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?
Also see:
How can I list the methods in a
Python 2.5 module?
Looping over
a Python / IronPython Object
Methods
Finding the methods an
object has
How do I look inside
a Python object?
How Do I
Perform Introspection on an Object in
Python 2.x?
How to get a
complete list of object’s methods and
attributes?- Finding out which
functions are available from a class
instance in python?
python
I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?
Also see:
How can I list the methods in a
Python 2.5 module?
Looping over
a Python / IronPython Object
Methods
Finding the methods an
object has
How do I look inside
a Python object?
How Do I
Perform Introspection on an Object in
Python 2.x?
How to get a
complete list of object’s methods and
attributes?- Finding out which
functions are available from a class
instance in python?
python
python
edited May 23 '17 at 12:10
Community♦
11
11
asked Dec 15 '09 at 23:40
PurrellPurrell
5,922154663
5,922154663
43
@S.Lott Why can't you use the Force? What's wrong with the Force?
– jononomo
Jan 4 '13 at 0:51
1
The source..... the source...
– RickyA
Oct 9 '13 at 15:25
3
@JonCrowell that's not how the Force works.
– Ken Williams
Apr 24 '17 at 3:24
For Cython using the compiler directivebinding
works: stackoverflow.com/a/46041480/1959808
– Ioannis Filippidis
Sep 9 '17 at 7:46
On python3:[f for f in dir(ClassName) if not f.startswith('_')]
or justdir(ClassName)
for everything
– Seraf
Feb 7 at 16:23
add a comment |
43
@S.Lott Why can't you use the Force? What's wrong with the Force?
– jononomo
Jan 4 '13 at 0:51
1
The source..... the source...
– RickyA
Oct 9 '13 at 15:25
3
@JonCrowell that's not how the Force works.
– Ken Williams
Apr 24 '17 at 3:24
For Cython using the compiler directivebinding
works: stackoverflow.com/a/46041480/1959808
– Ioannis Filippidis
Sep 9 '17 at 7:46
On python3:[f for f in dir(ClassName) if not f.startswith('_')]
or justdir(ClassName)
for everything
– Seraf
Feb 7 at 16:23
43
43
@S.Lott Why can't you use the Force? What's wrong with the Force?
– jononomo
Jan 4 '13 at 0:51
@S.Lott Why can't you use the Force? What's wrong with the Force?
– jononomo
Jan 4 '13 at 0:51
1
1
The source..... the source...
– RickyA
Oct 9 '13 at 15:25
The source..... the source...
– RickyA
Oct 9 '13 at 15:25
3
3
@JonCrowell that's not how the Force works.
– Ken Williams
Apr 24 '17 at 3:24
@JonCrowell that's not how the Force works.
– Ken Williams
Apr 24 '17 at 3:24
For Cython using the compiler directive
binding
works: stackoverflow.com/a/46041480/1959808– Ioannis Filippidis
Sep 9 '17 at 7:46
For Cython using the compiler directive
binding
works: stackoverflow.com/a/46041480/1959808– Ioannis Filippidis
Sep 9 '17 at 7:46
On python3:
[f for f in dir(ClassName) if not f.startswith('_')]
or just dir(ClassName)
for everything– Seraf
Feb 7 at 16:23
On python3:
[f for f in dir(ClassName) if not f.startswith('_')]
or just dir(ClassName)
for everything– Seraf
Feb 7 at 16:23
add a comment |
13 Answers
13
active
oldest
votes
An example (listing the methods of the optparse.OptionParser
class):
>>> from optparse import OptionParser
>>> import inspect
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
('add_option', <unbound method OptionParser.add_option>),
('add_option_group', <unbound method OptionParser.add_option_group>),
('add_options', <unbound method OptionParser.add_options>),
('check_values', <unbound method OptionParser.check_values>),
('destroy', <unbound method OptionParser.destroy>),
('disable_interspersed_args',
<unbound method OptionParser.disable_interspersed_args>),
('enable_interspersed_args',
<unbound method OptionParser.enable_interspersed_args>),
('error', <unbound method OptionParser.error>),
('exit', <unbound method OptionParser.exit>),
('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
...
]
Notice that getmembers
returns a list of 2-tuples. The first item is the name of the member, the second item is the value.
You can also pass an instance to getmembers
:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...
4
perfect, the predicate part is key, otherwise you get the same thing as dict with the extra meta info. Thanks.
– Purrell
Dec 15 '09 at 23:48
1
Will this produce a list of all methods in the class (including ones that are inherited from other classes), or will it only list the methods that are explicitly defined in that class?
– Anderson Green
Mar 10 '13 at 23:21
It includes inherited methods.
– codeape
Mar 12 '13 at 7:11
This only gives me the base class's methods, not the classes of the derived's.. - Update: this is because all methods in derived were static.
– poli_g
Mar 29 '15 at 10:34
6
inspect.isroutine
might be a more appropriate predicate;inspect.ismethod
doesn't work for all objects' methods.
– g.rocket
Jul 14 '17 at 22:40
|
show 4 more comments
There is the dir(theobject)
method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """).
Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods. You might want to try if the object you get through dir
is callable or not.
add a comment |
Python 3.x answer without external libraries
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
dunder-excluded result:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
add a comment |
Try the property __dict__
.
12
I think you mean dict. But that lists the attributes of the instance, not the methods.
– me_and
Dec 15 '09 at 23:45
1
…that didn't work for me either. Having consulted the Markdown syntax, I think I mean __dict__.
– me_and
Dec 15 '09 at 23:48
3
@me_and you're probably doing "self.__dict__" or, more generically, calling the instance version of__dict__
. However classes have a__dict__
too and that should display the class methods :)
– Seaux
Mar 29 '15 at 18:42
3
Maybe remove this incorrect answer?
– Ray Salemi
Mar 16 '18 at 20:10
add a comment |
you can also import the FunctionType from types and test it with the class.__dict__
:
from types import FunctionType
class Foo:
def bar(self): pass
def baz(self): pass
def methods(cls):
return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
methods(Foo) # ['bar', 'baz']
This worked well for me. I did addand not x.startswith('_')
to the end of the list comprehension for my use to ignore__init__
's and private methods.
– Christopher Pearson
May 10 '15 at 22:40
1
You can get rid of theimport
ofFunctionType
by using a throwaway lambda withtype()
:type(lambda:0)
– Tersosauros
Apr 7 '16 at 12:06
isinstance
would be the better thantype(y) == FunctionType
here.
– Jacco van Dorp
Oct 25 '18 at 7:22
add a comment |
Note that you need to consider whether you want methods from base classes which are inherited (but not overridden) included in the result. The dir()
and inspect.getmembers()
operations do include base class methods, but use of the __dict__
attribute does not.
add a comment |
Say you want to know all methods associated with list class
Just Type The following
print (dir(list))
Above will give you all methods of list class
2
This one is the best solution
– Zeeshan Ahmad
Jan 11 at 7:38
print([ m for m in dir(my_class) if not m.startswith('__')])
– Evhz
yesterday
add a comment |
def find_defining_class(obj, meth_name):
for ty in type(obj).mro():
if meth_name in ty.__dict__:
return ty
So
print find_defining_class(car, 'speedometer')
Think Python page 210
2
Indentation of 5? Capitalizing keywords? Non-pep8-style spacing?
– Florrie
Dec 5 '15 at 15:57
Not once the coding convention nazis got to it!
– rbennell
Jul 27 '17 at 11:37
add a comment |
This also works:
mymodule.py
def foo(x)
return 'foo'
def bar()
return 'bar'
In another file
import inspect
import mymodule
method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]
output:
['foo', 'bar']
From the python docs:
inspect.isroutine(object)
Return true if the object is a user-defined or built-in function or method.
add a comment |
If you want to list only methods of a python class
import numpy as np
print(np.random.__all__)
add a comment |
I know this is an old post, but just wrote this function and will leave it here is case someone stumbles looking for an answer:
def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):
def acceptMethod(tup):
#internal function that analyzes the tuples returned by getmembers tup[1] is the
#actual member object
is_method = inspect.ismethod(tup[1])
if is_method:
bound_to = tup[1].im_self
internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
if internal and exclude_internal:
include = False
else:
include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
else:
include = False
return include
#uses filter to return results according to internal function and arguments
return filter(acceptMethod,inspect.getmembers(the_class))
This code does not do what it is intended as published. Giving class_only or instance_only will result in empty list.
– Oz123
Jul 15 '16 at 13:22
add a comment |
If your method is a "regular" method and not a statimethod
, classmethod
etc.
There is a little hack I came up with -
for k, v in your_class.__dict__.items():
if "function" in str(v):
print(k)
This can be extended to other type of methods by changing "function" in the if
condition correspondingly.
Tested on python 2.7.
add a comment |
class CPerson:
def __init__(self, age):
self._age = age
def run(self):
pass
@property
def age(self): return self._age
@staticmethod
def my_static_method(): print("Life is short, you need Python")
@classmethod
def say(cls, msg): return msg
test_class = CPerson
# print(dir(test_class)) # list all the fields and methods of your object
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ == 'function' and not name.startswith('__')])
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ != 'function' and not name.startswith('__')])
output
[('run', <function CPerson.run at 0x0000000002AD3268>)]
[('age', <property object at 0x0000000002368688>), ('my_static_method', <staticmethod object at 0x0000000002ACBD68>), ('say', <classmethod object at 0x0000000002ACF0B8>)]
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1911281%2fhow-do-i-get-list-of-methods-in-a-python-class%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
13 Answers
13
active
oldest
votes
13 Answers
13
active
oldest
votes
active
oldest
votes
active
oldest
votes
An example (listing the methods of the optparse.OptionParser
class):
>>> from optparse import OptionParser
>>> import inspect
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
('add_option', <unbound method OptionParser.add_option>),
('add_option_group', <unbound method OptionParser.add_option_group>),
('add_options', <unbound method OptionParser.add_options>),
('check_values', <unbound method OptionParser.check_values>),
('destroy', <unbound method OptionParser.destroy>),
('disable_interspersed_args',
<unbound method OptionParser.disable_interspersed_args>),
('enable_interspersed_args',
<unbound method OptionParser.enable_interspersed_args>),
('error', <unbound method OptionParser.error>),
('exit', <unbound method OptionParser.exit>),
('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
...
]
Notice that getmembers
returns a list of 2-tuples. The first item is the name of the member, the second item is the value.
You can also pass an instance to getmembers
:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...
4
perfect, the predicate part is key, otherwise you get the same thing as dict with the extra meta info. Thanks.
– Purrell
Dec 15 '09 at 23:48
1
Will this produce a list of all methods in the class (including ones that are inherited from other classes), or will it only list the methods that are explicitly defined in that class?
– Anderson Green
Mar 10 '13 at 23:21
It includes inherited methods.
– codeape
Mar 12 '13 at 7:11
This only gives me the base class's methods, not the classes of the derived's.. - Update: this is because all methods in derived were static.
– poli_g
Mar 29 '15 at 10:34
6
inspect.isroutine
might be a more appropriate predicate;inspect.ismethod
doesn't work for all objects' methods.
– g.rocket
Jul 14 '17 at 22:40
|
show 4 more comments
An example (listing the methods of the optparse.OptionParser
class):
>>> from optparse import OptionParser
>>> import inspect
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
('add_option', <unbound method OptionParser.add_option>),
('add_option_group', <unbound method OptionParser.add_option_group>),
('add_options', <unbound method OptionParser.add_options>),
('check_values', <unbound method OptionParser.check_values>),
('destroy', <unbound method OptionParser.destroy>),
('disable_interspersed_args',
<unbound method OptionParser.disable_interspersed_args>),
('enable_interspersed_args',
<unbound method OptionParser.enable_interspersed_args>),
('error', <unbound method OptionParser.error>),
('exit', <unbound method OptionParser.exit>),
('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
...
]
Notice that getmembers
returns a list of 2-tuples. The first item is the name of the member, the second item is the value.
You can also pass an instance to getmembers
:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...
4
perfect, the predicate part is key, otherwise you get the same thing as dict with the extra meta info. Thanks.
– Purrell
Dec 15 '09 at 23:48
1
Will this produce a list of all methods in the class (including ones that are inherited from other classes), or will it only list the methods that are explicitly defined in that class?
– Anderson Green
Mar 10 '13 at 23:21
It includes inherited methods.
– codeape
Mar 12 '13 at 7:11
This only gives me the base class's methods, not the classes of the derived's.. - Update: this is because all methods in derived were static.
– poli_g
Mar 29 '15 at 10:34
6
inspect.isroutine
might be a more appropriate predicate;inspect.ismethod
doesn't work for all objects' methods.
– g.rocket
Jul 14 '17 at 22:40
|
show 4 more comments
An example (listing the methods of the optparse.OptionParser
class):
>>> from optparse import OptionParser
>>> import inspect
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
('add_option', <unbound method OptionParser.add_option>),
('add_option_group', <unbound method OptionParser.add_option_group>),
('add_options', <unbound method OptionParser.add_options>),
('check_values', <unbound method OptionParser.check_values>),
('destroy', <unbound method OptionParser.destroy>),
('disable_interspersed_args',
<unbound method OptionParser.disable_interspersed_args>),
('enable_interspersed_args',
<unbound method OptionParser.enable_interspersed_args>),
('error', <unbound method OptionParser.error>),
('exit', <unbound method OptionParser.exit>),
('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
...
]
Notice that getmembers
returns a list of 2-tuples. The first item is the name of the member, the second item is the value.
You can also pass an instance to getmembers
:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...
An example (listing the methods of the optparse.OptionParser
class):
>>> from optparse import OptionParser
>>> import inspect
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
('add_option', <unbound method OptionParser.add_option>),
('add_option_group', <unbound method OptionParser.add_option_group>),
('add_options', <unbound method OptionParser.add_options>),
('check_values', <unbound method OptionParser.check_values>),
('destroy', <unbound method OptionParser.destroy>),
('disable_interspersed_args',
<unbound method OptionParser.disable_interspersed_args>),
('enable_interspersed_args',
<unbound method OptionParser.enable_interspersed_args>),
('error', <unbound method OptionParser.error>),
('exit', <unbound method OptionParser.exit>),
('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
...
]
Notice that getmembers
returns a list of 2-tuples. The first item is the name of the member, the second item is the value.
You can also pass an instance to getmembers
:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...
edited Aug 12 '14 at 16:00
the Tin Man
136k27173256
136k27173256
answered Dec 15 '09 at 23:41
codeapecodeape
73.3k20123149
73.3k20123149
4
perfect, the predicate part is key, otherwise you get the same thing as dict with the extra meta info. Thanks.
– Purrell
Dec 15 '09 at 23:48
1
Will this produce a list of all methods in the class (including ones that are inherited from other classes), or will it only list the methods that are explicitly defined in that class?
– Anderson Green
Mar 10 '13 at 23:21
It includes inherited methods.
– codeape
Mar 12 '13 at 7:11
This only gives me the base class's methods, not the classes of the derived's.. - Update: this is because all methods in derived were static.
– poli_g
Mar 29 '15 at 10:34
6
inspect.isroutine
might be a more appropriate predicate;inspect.ismethod
doesn't work for all objects' methods.
– g.rocket
Jul 14 '17 at 22:40
|
show 4 more comments
4
perfect, the predicate part is key, otherwise you get the same thing as dict with the extra meta info. Thanks.
– Purrell
Dec 15 '09 at 23:48
1
Will this produce a list of all methods in the class (including ones that are inherited from other classes), or will it only list the methods that are explicitly defined in that class?
– Anderson Green
Mar 10 '13 at 23:21
It includes inherited methods.
– codeape
Mar 12 '13 at 7:11
This only gives me the base class's methods, not the classes of the derived's.. - Update: this is because all methods in derived were static.
– poli_g
Mar 29 '15 at 10:34
6
inspect.isroutine
might be a more appropriate predicate;inspect.ismethod
doesn't work for all objects' methods.
– g.rocket
Jul 14 '17 at 22:40
4
4
perfect, the predicate part is key, otherwise you get the same thing as dict with the extra meta info. Thanks.
– Purrell
Dec 15 '09 at 23:48
perfect, the predicate part is key, otherwise you get the same thing as dict with the extra meta info. Thanks.
– Purrell
Dec 15 '09 at 23:48
1
1
Will this produce a list of all methods in the class (including ones that are inherited from other classes), or will it only list the methods that are explicitly defined in that class?
– Anderson Green
Mar 10 '13 at 23:21
Will this produce a list of all methods in the class (including ones that are inherited from other classes), or will it only list the methods that are explicitly defined in that class?
– Anderson Green
Mar 10 '13 at 23:21
It includes inherited methods.
– codeape
Mar 12 '13 at 7:11
It includes inherited methods.
– codeape
Mar 12 '13 at 7:11
This only gives me the base class's methods, not the classes of the derived's.. - Update: this is because all methods in derived were static.
– poli_g
Mar 29 '15 at 10:34
This only gives me the base class's methods, not the classes of the derived's.. - Update: this is because all methods in derived were static.
– poli_g
Mar 29 '15 at 10:34
6
6
inspect.isroutine
might be a more appropriate predicate; inspect.ismethod
doesn't work for all objects' methods.– g.rocket
Jul 14 '17 at 22:40
inspect.isroutine
might be a more appropriate predicate; inspect.ismethod
doesn't work for all objects' methods.– g.rocket
Jul 14 '17 at 22:40
|
show 4 more comments
There is the dir(theobject)
method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """).
Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods. You might want to try if the object you get through dir
is callable or not.
add a comment |
There is the dir(theobject)
method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """).
Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods. You might want to try if the object you get through dir
is callable or not.
add a comment |
There is the dir(theobject)
method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """).
Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods. You might want to try if the object you get through dir
is callable or not.
There is the dir(theobject)
method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """).
Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods. You might want to try if the object you get through dir
is callable or not.
edited Aug 12 '14 at 16:02
the Tin Man
136k27173256
136k27173256
answered Dec 15 '09 at 23:49
Vincent DemeesterVincent Demeester
4,93731615
4,93731615
add a comment |
add a comment |
Python 3.x answer without external libraries
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
dunder-excluded result:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
add a comment |
Python 3.x answer without external libraries
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
dunder-excluded result:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
add a comment |
Python 3.x answer without external libraries
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
dunder-excluded result:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
Python 3.x answer without external libraries
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
dunder-excluded result:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
answered Aug 21 '16 at 7:33
DerorristDerorrist
974616
974616
add a comment |
add a comment |
Try the property __dict__
.
12
I think you mean dict. But that lists the attributes of the instance, not the methods.
– me_and
Dec 15 '09 at 23:45
1
…that didn't work for me either. Having consulted the Markdown syntax, I think I mean __dict__.
– me_and
Dec 15 '09 at 23:48
3
@me_and you're probably doing "self.__dict__" or, more generically, calling the instance version of__dict__
. However classes have a__dict__
too and that should display the class methods :)
– Seaux
Mar 29 '15 at 18:42
3
Maybe remove this incorrect answer?
– Ray Salemi
Mar 16 '18 at 20:10
add a comment |
Try the property __dict__
.
12
I think you mean dict. But that lists the attributes of the instance, not the methods.
– me_and
Dec 15 '09 at 23:45
1
…that didn't work for me either. Having consulted the Markdown syntax, I think I mean __dict__.
– me_and
Dec 15 '09 at 23:48
3
@me_and you're probably doing "self.__dict__" or, more generically, calling the instance version of__dict__
. However classes have a__dict__
too and that should display the class methods :)
– Seaux
Mar 29 '15 at 18:42
3
Maybe remove this incorrect answer?
– Ray Salemi
Mar 16 '18 at 20:10
add a comment |
Try the property __dict__
.
Try the property __dict__
.
answered Dec 15 '09 at 23:42
Eugene BulkinEugene Bulkin
76111114
76111114
12
I think you mean dict. But that lists the attributes of the instance, not the methods.
– me_and
Dec 15 '09 at 23:45
1
…that didn't work for me either. Having consulted the Markdown syntax, I think I mean __dict__.
– me_and
Dec 15 '09 at 23:48
3
@me_and you're probably doing "self.__dict__" or, more generically, calling the instance version of__dict__
. However classes have a__dict__
too and that should display the class methods :)
– Seaux
Mar 29 '15 at 18:42
3
Maybe remove this incorrect answer?
– Ray Salemi
Mar 16 '18 at 20:10
add a comment |
12
I think you mean dict. But that lists the attributes of the instance, not the methods.
– me_and
Dec 15 '09 at 23:45
1
…that didn't work for me either. Having consulted the Markdown syntax, I think I mean __dict__.
– me_and
Dec 15 '09 at 23:48
3
@me_and you're probably doing "self.__dict__" or, more generically, calling the instance version of__dict__
. However classes have a__dict__
too and that should display the class methods :)
– Seaux
Mar 29 '15 at 18:42
3
Maybe remove this incorrect answer?
– Ray Salemi
Mar 16 '18 at 20:10
12
12
I think you mean dict. But that lists the attributes of the instance, not the methods.
– me_and
Dec 15 '09 at 23:45
I think you mean dict. But that lists the attributes of the instance, not the methods.
– me_and
Dec 15 '09 at 23:45
1
1
…that didn't work for me either. Having consulted the Markdown syntax, I think I mean __dict__.
– me_and
Dec 15 '09 at 23:48
…that didn't work for me either. Having consulted the Markdown syntax, I think I mean __dict__.
– me_and
Dec 15 '09 at 23:48
3
3
@me_and you're probably doing "self.__dict__" or, more generically, calling the instance version of
__dict__
. However classes have a __dict__
too and that should display the class methods :)– Seaux
Mar 29 '15 at 18:42
@me_and you're probably doing "self.__dict__" or, more generically, calling the instance version of
__dict__
. However classes have a __dict__
too and that should display the class methods :)– Seaux
Mar 29 '15 at 18:42
3
3
Maybe remove this incorrect answer?
– Ray Salemi
Mar 16 '18 at 20:10
Maybe remove this incorrect answer?
– Ray Salemi
Mar 16 '18 at 20:10
add a comment |
you can also import the FunctionType from types and test it with the class.__dict__
:
from types import FunctionType
class Foo:
def bar(self): pass
def baz(self): pass
def methods(cls):
return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
methods(Foo) # ['bar', 'baz']
This worked well for me. I did addand not x.startswith('_')
to the end of the list comprehension for my use to ignore__init__
's and private methods.
– Christopher Pearson
May 10 '15 at 22:40
1
You can get rid of theimport
ofFunctionType
by using a throwaway lambda withtype()
:type(lambda:0)
– Tersosauros
Apr 7 '16 at 12:06
isinstance
would be the better thantype(y) == FunctionType
here.
– Jacco van Dorp
Oct 25 '18 at 7:22
add a comment |
you can also import the FunctionType from types and test it with the class.__dict__
:
from types import FunctionType
class Foo:
def bar(self): pass
def baz(self): pass
def methods(cls):
return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
methods(Foo) # ['bar', 'baz']
This worked well for me. I did addand not x.startswith('_')
to the end of the list comprehension for my use to ignore__init__
's and private methods.
– Christopher Pearson
May 10 '15 at 22:40
1
You can get rid of theimport
ofFunctionType
by using a throwaway lambda withtype()
:type(lambda:0)
– Tersosauros
Apr 7 '16 at 12:06
isinstance
would be the better thantype(y) == FunctionType
here.
– Jacco van Dorp
Oct 25 '18 at 7:22
add a comment |
you can also import the FunctionType from types and test it with the class.__dict__
:
from types import FunctionType
class Foo:
def bar(self): pass
def baz(self): pass
def methods(cls):
return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
methods(Foo) # ['bar', 'baz']
you can also import the FunctionType from types and test it with the class.__dict__
:
from types import FunctionType
class Foo:
def bar(self): pass
def baz(self): pass
def methods(cls):
return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
methods(Foo) # ['bar', 'baz']
edited Aug 15 '16 at 14:45
tleb
2,75411730
2,75411730
answered Mar 29 '15 at 18:58
SeauxSeaux
2,63021927
2,63021927
This worked well for me. I did addand not x.startswith('_')
to the end of the list comprehension for my use to ignore__init__
's and private methods.
– Christopher Pearson
May 10 '15 at 22:40
1
You can get rid of theimport
ofFunctionType
by using a throwaway lambda withtype()
:type(lambda:0)
– Tersosauros
Apr 7 '16 at 12:06
isinstance
would be the better thantype(y) == FunctionType
here.
– Jacco van Dorp
Oct 25 '18 at 7:22
add a comment |
This worked well for me. I did addand not x.startswith('_')
to the end of the list comprehension for my use to ignore__init__
's and private methods.
– Christopher Pearson
May 10 '15 at 22:40
1
You can get rid of theimport
ofFunctionType
by using a throwaway lambda withtype()
:type(lambda:0)
– Tersosauros
Apr 7 '16 at 12:06
isinstance
would be the better thantype(y) == FunctionType
here.
– Jacco van Dorp
Oct 25 '18 at 7:22
This worked well for me. I did add
and not x.startswith('_')
to the end of the list comprehension for my use to ignore __init__
's and private methods.– Christopher Pearson
May 10 '15 at 22:40
This worked well for me. I did add
and not x.startswith('_')
to the end of the list comprehension for my use to ignore __init__
's and private methods.– Christopher Pearson
May 10 '15 at 22:40
1
1
You can get rid of the
import
of FunctionType
by using a throwaway lambda with type()
: type(lambda:0)
– Tersosauros
Apr 7 '16 at 12:06
You can get rid of the
import
of FunctionType
by using a throwaway lambda with type()
: type(lambda:0)
– Tersosauros
Apr 7 '16 at 12:06
isinstance
would be the better than type(y) == FunctionType
here.– Jacco van Dorp
Oct 25 '18 at 7:22
isinstance
would be the better than type(y) == FunctionType
here.– Jacco van Dorp
Oct 25 '18 at 7:22
add a comment |
Note that you need to consider whether you want methods from base classes which are inherited (but not overridden) included in the result. The dir()
and inspect.getmembers()
operations do include base class methods, but use of the __dict__
attribute does not.
add a comment |
Note that you need to consider whether you want methods from base classes which are inherited (but not overridden) included in the result. The dir()
and inspect.getmembers()
operations do include base class methods, but use of the __dict__
attribute does not.
add a comment |
Note that you need to consider whether you want methods from base classes which are inherited (but not overridden) included in the result. The dir()
and inspect.getmembers()
operations do include base class methods, but use of the __dict__
attribute does not.
Note that you need to consider whether you want methods from base classes which are inherited (but not overridden) included in the result. The dir()
and inspect.getmembers()
operations do include base class methods, but use of the __dict__
attribute does not.
edited Aug 12 '14 at 16:01
the Tin Man
136k27173256
136k27173256
answered Sep 20 '11 at 0:21
satyagrahasatyagraha
458411
458411
add a comment |
add a comment |
Say you want to know all methods associated with list class
Just Type The following
print (dir(list))
Above will give you all methods of list class
2
This one is the best solution
– Zeeshan Ahmad
Jan 11 at 7:38
print([ m for m in dir(my_class) if not m.startswith('__')])
– Evhz
yesterday
add a comment |
Say you want to know all methods associated with list class
Just Type The following
print (dir(list))
Above will give you all methods of list class
2
This one is the best solution
– Zeeshan Ahmad
Jan 11 at 7:38
print([ m for m in dir(my_class) if not m.startswith('__')])
– Evhz
yesterday
add a comment |
Say you want to know all methods associated with list class
Just Type The following
print (dir(list))
Above will give you all methods of list class
Say you want to know all methods associated with list class
Just Type The following
print (dir(list))
Above will give you all methods of list class
answered Dec 4 '18 at 8:28
Naresh JoshiNaresh Joshi
9111
9111
2
This one is the best solution
– Zeeshan Ahmad
Jan 11 at 7:38
print([ m for m in dir(my_class) if not m.startswith('__')])
– Evhz
yesterday
add a comment |
2
This one is the best solution
– Zeeshan Ahmad
Jan 11 at 7:38
print([ m for m in dir(my_class) if not m.startswith('__')])
– Evhz
yesterday
2
2
This one is the best solution
– Zeeshan Ahmad
Jan 11 at 7:38
This one is the best solution
– Zeeshan Ahmad
Jan 11 at 7:38
print([ m for m in dir(my_class) if not m.startswith('__')])
– Evhz
yesterday
print([ m for m in dir(my_class) if not m.startswith('__')])
– Evhz
yesterday
add a comment |
def find_defining_class(obj, meth_name):
for ty in type(obj).mro():
if meth_name in ty.__dict__:
return ty
So
print find_defining_class(car, 'speedometer')
Think Python page 210
2
Indentation of 5? Capitalizing keywords? Non-pep8-style spacing?
– Florrie
Dec 5 '15 at 15:57
Not once the coding convention nazis got to it!
– rbennell
Jul 27 '17 at 11:37
add a comment |
def find_defining_class(obj, meth_name):
for ty in type(obj).mro():
if meth_name in ty.__dict__:
return ty
So
print find_defining_class(car, 'speedometer')
Think Python page 210
2
Indentation of 5? Capitalizing keywords? Non-pep8-style spacing?
– Florrie
Dec 5 '15 at 15:57
Not once the coding convention nazis got to it!
– rbennell
Jul 27 '17 at 11:37
add a comment |
def find_defining_class(obj, meth_name):
for ty in type(obj).mro():
if meth_name in ty.__dict__:
return ty
So
print find_defining_class(car, 'speedometer')
Think Python page 210
def find_defining_class(obj, meth_name):
for ty in type(obj).mro():
if meth_name in ty.__dict__:
return ty
So
print find_defining_class(car, 'speedometer')
Think Python page 210
edited Apr 6 '16 at 21:38
Kara
4,034104353
4,034104353
answered Jul 12 '14 at 16:41
lewis scott diamondlewis scott diamond
312
312
2
Indentation of 5? Capitalizing keywords? Non-pep8-style spacing?
– Florrie
Dec 5 '15 at 15:57
Not once the coding convention nazis got to it!
– rbennell
Jul 27 '17 at 11:37
add a comment |
2
Indentation of 5? Capitalizing keywords? Non-pep8-style spacing?
– Florrie
Dec 5 '15 at 15:57
Not once the coding convention nazis got to it!
– rbennell
Jul 27 '17 at 11:37
2
2
Indentation of 5? Capitalizing keywords? Non-pep8-style spacing?
– Florrie
Dec 5 '15 at 15:57
Indentation of 5? Capitalizing keywords? Non-pep8-style spacing?
– Florrie
Dec 5 '15 at 15:57
Not once the coding convention nazis got to it!
– rbennell
Jul 27 '17 at 11:37
Not once the coding convention nazis got to it!
– rbennell
Jul 27 '17 at 11:37
add a comment |
This also works:
mymodule.py
def foo(x)
return 'foo'
def bar()
return 'bar'
In another file
import inspect
import mymodule
method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]
output:
['foo', 'bar']
From the python docs:
inspect.isroutine(object)
Return true if the object is a user-defined or built-in function or method.
add a comment |
This also works:
mymodule.py
def foo(x)
return 'foo'
def bar()
return 'bar'
In another file
import inspect
import mymodule
method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]
output:
['foo', 'bar']
From the python docs:
inspect.isroutine(object)
Return true if the object is a user-defined or built-in function or method.
add a comment |
This also works:
mymodule.py
def foo(x)
return 'foo'
def bar()
return 'bar'
In another file
import inspect
import mymodule
method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]
output:
['foo', 'bar']
From the python docs:
inspect.isroutine(object)
Return true if the object is a user-defined or built-in function or method.
This also works:
mymodule.py
def foo(x)
return 'foo'
def bar()
return 'bar'
In another file
import inspect
import mymodule
method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]
output:
['foo', 'bar']
From the python docs:
inspect.isroutine(object)
Return true if the object is a user-defined or built-in function or method.
edited Jan 23 at 11:25
answered Jan 23 at 11:19
Josh DandoJosh Dando
21124
21124
add a comment |
add a comment |
If you want to list only methods of a python class
import numpy as np
print(np.random.__all__)
add a comment |
If you want to list only methods of a python class
import numpy as np
print(np.random.__all__)
add a comment |
If you want to list only methods of a python class
import numpy as np
print(np.random.__all__)
If you want to list only methods of a python class
import numpy as np
print(np.random.__all__)
answered Mar 25 at 6:46
Rakesh ChaudhariRakesh Chaudhari
1,11711420
1,11711420
add a comment |
add a comment |
I know this is an old post, but just wrote this function and will leave it here is case someone stumbles looking for an answer:
def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):
def acceptMethod(tup):
#internal function that analyzes the tuples returned by getmembers tup[1] is the
#actual member object
is_method = inspect.ismethod(tup[1])
if is_method:
bound_to = tup[1].im_self
internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
if internal and exclude_internal:
include = False
else:
include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
else:
include = False
return include
#uses filter to return results according to internal function and arguments
return filter(acceptMethod,inspect.getmembers(the_class))
This code does not do what it is intended as published. Giving class_only or instance_only will result in empty list.
– Oz123
Jul 15 '16 at 13:22
add a comment |
I know this is an old post, but just wrote this function and will leave it here is case someone stumbles looking for an answer:
def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):
def acceptMethod(tup):
#internal function that analyzes the tuples returned by getmembers tup[1] is the
#actual member object
is_method = inspect.ismethod(tup[1])
if is_method:
bound_to = tup[1].im_self
internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
if internal and exclude_internal:
include = False
else:
include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
else:
include = False
return include
#uses filter to return results according to internal function and arguments
return filter(acceptMethod,inspect.getmembers(the_class))
This code does not do what it is intended as published. Giving class_only or instance_only will result in empty list.
– Oz123
Jul 15 '16 at 13:22
add a comment |
I know this is an old post, but just wrote this function and will leave it here is case someone stumbles looking for an answer:
def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):
def acceptMethod(tup):
#internal function that analyzes the tuples returned by getmembers tup[1] is the
#actual member object
is_method = inspect.ismethod(tup[1])
if is_method:
bound_to = tup[1].im_self
internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
if internal and exclude_internal:
include = False
else:
include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
else:
include = False
return include
#uses filter to return results according to internal function and arguments
return filter(acceptMethod,inspect.getmembers(the_class))
I know this is an old post, but just wrote this function and will leave it here is case someone stumbles looking for an answer:
def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):
def acceptMethod(tup):
#internal function that analyzes the tuples returned by getmembers tup[1] is the
#actual member object
is_method = inspect.ismethod(tup[1])
if is_method:
bound_to = tup[1].im_self
internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
if internal and exclude_internal:
include = False
else:
include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
else:
include = False
return include
#uses filter to return results according to internal function and arguments
return filter(acceptMethod,inspect.getmembers(the_class))
edited Aug 12 '14 at 16:01
the Tin Man
136k27173256
136k27173256
answered Jul 17 '14 at 5:57
user3569372user3569372
144
144
This code does not do what it is intended as published. Giving class_only or instance_only will result in empty list.
– Oz123
Jul 15 '16 at 13:22
add a comment |
This code does not do what it is intended as published. Giving class_only or instance_only will result in empty list.
– Oz123
Jul 15 '16 at 13:22
This code does not do what it is intended as published. Giving class_only or instance_only will result in empty list.
– Oz123
Jul 15 '16 at 13:22
This code does not do what it is intended as published. Giving class_only or instance_only will result in empty list.
– Oz123
Jul 15 '16 at 13:22
add a comment |
If your method is a "regular" method and not a statimethod
, classmethod
etc.
There is a little hack I came up with -
for k, v in your_class.__dict__.items():
if "function" in str(v):
print(k)
This can be extended to other type of methods by changing "function" in the if
condition correspondingly.
Tested on python 2.7.
add a comment |
If your method is a "regular" method and not a statimethod
, classmethod
etc.
There is a little hack I came up with -
for k, v in your_class.__dict__.items():
if "function" in str(v):
print(k)
This can be extended to other type of methods by changing "function" in the if
condition correspondingly.
Tested on python 2.7.
add a comment |
If your method is a "regular" method and not a statimethod
, classmethod
etc.
There is a little hack I came up with -
for k, v in your_class.__dict__.items():
if "function" in str(v):
print(k)
This can be extended to other type of methods by changing "function" in the if
condition correspondingly.
Tested on python 2.7.
If your method is a "regular" method and not a statimethod
, classmethod
etc.
There is a little hack I came up with -
for k, v in your_class.__dict__.items():
if "function" in str(v):
print(k)
This can be extended to other type of methods by changing "function" in the if
condition correspondingly.
Tested on python 2.7.
answered May 4 '18 at 16:30
markroxormarkroxor
1,6141024
1,6141024
add a comment |
add a comment |
class CPerson:
def __init__(self, age):
self._age = age
def run(self):
pass
@property
def age(self): return self._age
@staticmethod
def my_static_method(): print("Life is short, you need Python")
@classmethod
def say(cls, msg): return msg
test_class = CPerson
# print(dir(test_class)) # list all the fields and methods of your object
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ == 'function' and not name.startswith('__')])
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ != 'function' and not name.startswith('__')])
output
[('run', <function CPerson.run at 0x0000000002AD3268>)]
[('age', <property object at 0x0000000002368688>), ('my_static_method', <staticmethod object at 0x0000000002ACBD68>), ('say', <classmethod object at 0x0000000002ACF0B8>)]
add a comment |
class CPerson:
def __init__(self, age):
self._age = age
def run(self):
pass
@property
def age(self): return self._age
@staticmethod
def my_static_method(): print("Life is short, you need Python")
@classmethod
def say(cls, msg): return msg
test_class = CPerson
# print(dir(test_class)) # list all the fields and methods of your object
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ == 'function' and not name.startswith('__')])
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ != 'function' and not name.startswith('__')])
output
[('run', <function CPerson.run at 0x0000000002AD3268>)]
[('age', <property object at 0x0000000002368688>), ('my_static_method', <staticmethod object at 0x0000000002ACBD68>), ('say', <classmethod object at 0x0000000002ACF0B8>)]
add a comment |
class CPerson:
def __init__(self, age):
self._age = age
def run(self):
pass
@property
def age(self): return self._age
@staticmethod
def my_static_method(): print("Life is short, you need Python")
@classmethod
def say(cls, msg): return msg
test_class = CPerson
# print(dir(test_class)) # list all the fields and methods of your object
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ == 'function' and not name.startswith('__')])
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ != 'function' and not name.startswith('__')])
output
[('run', <function CPerson.run at 0x0000000002AD3268>)]
[('age', <property object at 0x0000000002368688>), ('my_static_method', <staticmethod object at 0x0000000002ACBD68>), ('say', <classmethod object at 0x0000000002ACF0B8>)]
class CPerson:
def __init__(self, age):
self._age = age
def run(self):
pass
@property
def age(self): return self._age
@staticmethod
def my_static_method(): print("Life is short, you need Python")
@classmethod
def say(cls, msg): return msg
test_class = CPerson
# print(dir(test_class)) # list all the fields and methods of your object
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ == 'function' and not name.startswith('__')])
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ != 'function' and not name.startswith('__')])
output
[('run', <function CPerson.run at 0x0000000002AD3268>)]
[('age', <property object at 0x0000000002368688>), ('my_static_method', <staticmethod object at 0x0000000002ACBD68>), ('say', <classmethod object at 0x0000000002ACF0B8>)]
answered Mar 8 at 3:56
Carson ArucardCarson Arucard
1644
1644
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1911281%2fhow-do-i-get-list-of-methods-in-a-python-class%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
43
@S.Lott Why can't you use the Force? What's wrong with the Force?
– jononomo
Jan 4 '13 at 0:51
1
The source..... the source...
– RickyA
Oct 9 '13 at 15:25
3
@JonCrowell that's not how the Force works.
– Ken Williams
Apr 24 '17 at 3:24
For Cython using the compiler directive
binding
works: stackoverflow.com/a/46041480/1959808– Ioannis Filippidis
Sep 9 '17 at 7:46
On python3:
[f for f in dir(ClassName) if not f.startswith('_')]
or justdir(ClassName)
for everything– Seraf
Feb 7 at 16:23