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.
Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.
Defining Private Methods and Attributes To define a private attribute or method in python, you have to just prefix the name with a single underscore(_). Now, we will rewrite the above example to make “var” and “get_var” as private attributed.
Functions can be called only by its name, as it is defined independently. But methods can't be called by its name only, we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class.
Which of the following defines attributes and methods? Expert-verified answer In Java, a class contains many variable types and defines attributes and methods. A class is a blueprint that describes the state that the object of its type supports Individual objects are created from class.13-Aug-2018.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With