Nayan
Nayan

Reputation: 39

Confusion to figure out between attribute or method in Python

According to this following thread

How to differentiate between classes, functions, and methods

snake_case for functions and methods to determine if it's specific type.

I was looking at string module and I did print(dir(string)) and got all these

[Formatter, Template, _ChainMap, _TemplateMetaclass, __all__, __builtins__, __cached__, __doc__, __file__, __loader__, __name__, __package__, __spec__, _re, _sentinel_dict, _string, ascii_letters, ascii_lowercase, ascii_uppercase, capwords, digits, hexdigits, octdigits, printable, punctuation, whitespace]

I was just trying to get a range of alphabets using string.ascii_lowercase but is not ascii_lowercase a method according to the link mentioned above? and a method needs to be called as ascii_lowercase(). but it is not working , is their a clear way to distinguish what is what?

I am confused here , someone please help me out.

Edit 1: Just to be more clear on my question, an instance does usually have attributes and methods and even method is considered as an attribute to an instance , so this is where confusion arises for me.

Upvotes: 0

Views: 151

Answers (2)

Prune
Prune

Reputation: 77837

You can easily tell the difference by checking the type of the symbol. For instance:

>>> type(str.isupper)
<class 'method_descriptor'>
>>> type(string.ascii_lowercase)
<class 'str'>

Perhaps less direct, you read the package documentation.

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

string.ascii_lowercase holds the string value:

>>> import string

>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

To know the type of attribute, you can use type() on getattr(). Here's example to show type of all values returned by dir(string):

for x in dir(string):
    print("'{}' - {}".format(x, type(getattr(string, x))))

# which print the output as:
#   'Formatter' - <type 'type'>
#   'Template' - <class 'string._TemplateMetaclass'>
#   '_TemplateMetaclass' - <type 'type'>
#   '__builtins__' - <type 'dict'>
#   '__doc__' - <type 'str'>
#   '__file__' - <type 'str'>
# .... so on ....

Upvotes: 1

Related Questions