Reputation: 161674
Sometimes, I find it hard to distinguish between a method and an attribute by it's name without appending parentheses.
For example:
there're keys()
method and text
attribute in xml.etree.ElementTree.Element
class.
text
:The text attribute can be used to hold additional data associated with the element.
keys()
:Returns the elements attribute names as a list.
Is there some basic rules/conventions to make text
an attribute, but keys()
a method?
If I make text()
a method, and keys
an attribute. It still seems OK.
Upvotes: 6
Views: 265
Reputation: 176780
If you're talking about naming conventions, then in Python both are normally lowercase.
If you're talking about how to tell the two apart,
from collections import Callable, Container
if isinstance(attribute, Callable):
return attribute()
elif isinstance(attribute, str):
return attribute
elif isinstance(attribute, Container):
return 'Yes' if 'Blah' in attribute
else:
return str(attribute)
is how you check if a variable is pointed at a specific type of object
Upvotes: 2
Reputation: 56390
The only real distinction is that one is callable and one is not, so you can use the builtin function callable()
with the actual object (not a string with the name of it) to determine whether or not it is callable.
In your case:
>>> from xml.etree import ElementTree
>>> elt = ElementTree.Element("")
>>> callable(elt.keys)
True
>>> callable(elt.text)
False
Upvotes: 6