How to distinguish method and attribute in python by name

Sometimes it’s difficult for me to distinguish a method and an attribute from a name without adding parentheses.

For instance:
there is a keys() and text method in the xml.etree.ElementTree.Element class.

text : a text attribute can be used to store additional data associated with an element.

keys() : returns the attribute names of the elements in a list.


Are there some basic rules / conventions to make a text attribute but a keys() method?

If I create a text() method and keys attribute. It still seems OK.

+6
source share
2 answers

The only real difference is that one is called and the other is not, so you can use the callable() built-in function with the actual object (not a string with its name) to determine if it can be called.

In your case:

 >>> from xml.etree import ElementTree >>> elt = ElementTree.Element("") >>> callable(elt.keys) True >>> callable(elt.text) False 
+6
source

If you are talking about naming conventions, then in Python both are usually lowercase.

If you talk about how to tell each other,

 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 specified for a particular type of object

+2
source

Source: https://habr.com/ru/post/893790/


All Articles