Reputation: 414
This feels like a simple question, but I can't seem to figure out the answer after much searching. I'm wondering if, for instance, lists have attributes. By attributes I mean values that are accessed by dot notation (not methods). Do strings have them?
If I assign a string value to a variable:
test = 'test'
I tried dir(test)
, which returned a long list that included stuff like:
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
...]
(Note that I cut items off this list to abridge it.) What are the items with underscores? The other items seem to be methods. Are there any attributes? How would I identify an attribute?
Same question for instances of the list
class. How do I see all the available attributes of the class?
Upvotes: 0
Views: 107
Reputation: 64
I will add to the previous answer. The underscore methods are known as dunder methods (double underscore). Double underscore is used to prevent name collision with any functions names that a programmer might use.
These methods are usually called by python interpreter. For example __init__
is called by python during object instantiation. You can override these methods to change the functionality of the object. For example you can override __add__
method to add summation functionality to custom data types.
Upvotes: 1
Reputation: 182
Both methods and attributes are considered attributes in python, dir() lists them all. You can check what they are by doing
test = 'test'
for attr in dir(test):
print(f"{attr} : {type(getattr(test,attr))}")
Try it on this example, it will be more clear:
class TestClass:
def __init__(self,a):
self.a = a
def add_b(self, b):
return self.a + b
test = TestClass(10)
for attr in dir(test):
print(f"{attr} : {type(getattr(test,attr))}")
Upvotes: 1