Skip to content Skip to sidebar Skip to footer

How To Differentiate Between Classes, Functions, And Methods

In Python, the dir() function is used to display a list of attributes, classes, methods of the argument which is passed in to it, right ? For example there is a module email in pyt

Solution 1:

They're all attributes, some of those attributes might reference functions, some classes, or objects. The ones like __this__ are commonly called magic methods.

You can look at:

[type(getattr(email, x)) for x indir(email)]

But the best answer is: "What do I care?"

Any information you need to know about the interface is better found in the documentation of the module. The types of various attributes are of little use, low importance (and dir can be incomplete, too).

So don't bother type checking. It is worth knowing (and using) the python naming conventions though (see pep8):

  • CamelCase for classes
  • snake_case for functions and methods
  • SHOUTY_CASE for constants
  • _leading underscores for 'private' things (i.e. undocumented, implementation detail, not intended to be part of public interface)
  • __double leading underscores for enabling name mangling, it's a way to handle possible namespace collisions in complex inheritance situations (a very obscure feature that you almost certainly don't need in normal usage)
  • __dunder__ "double underscore" things for magic methods as mentioned previously, these are datamodel hooks for Python itself. You can redefine existing hooks to customize behaviour in your classes and modules, but don't invent new magic names just for your own purposes, use normal attributes instead.

Solution 2:

You can't, not "just by looking at the list". All of them are attributes. Some of them might also be methods, or functions, or classes, etc., but you can't tell by looking at the list. You have to look at the actual objects. For instance, you can use callable(email.Encoders) to decide if email.Encoders is callable. You can use type(email.Encoders) to find out what type that is. Or, more likely, you do none of these, because you know what methods/classes/functions you need to use, and you use them without using dir at all.

What are you actually trying to accomplish with your code?

Solution 3:

Is this what you're looking for?

[type(getattr(email, x)) for x in dir(email)]

Post a Comment for "How To Differentiate Between Classes, Functions, And Methods"