moltarze
moltarze

Reputation: 1501

Questions about default class functions in Python

Consider the following example of an iterative class which makes factorials from a given number:

import math

class Factorial(object):
  def __init__(self, num, maxsize=10e12):
    self.num = num
    self.maxsize = maxsize
  def __repr__(self):
    if __name__ == '__main__':
      return f'<{self.__class__.__name__} object at {hex(id(self.__class__))}>'
    else:
      return '<' + self.__class__.__module__ + '.' + self.__class__.__name__ + ' object at ' + hex(id(self.__class__)) + '>'
  def __iter__(self):
    for i in range(1,self.num+1):
      if math.factorial(i) > self.maxsize:
        break
      yield math.factorial(i)

So, of course we have the methods __init__, __repr__, and __iter__, which I have all read about online. I have two questions:

  1. What would you call these methods? I know you can describe __init__ as a sort of constructor, but is there a special name that all of those __<blah>__ methods fall under when it comes to classes?

  2. Is there a list of all of these so-called "special" or "built-in" class functions that tells what they are and what they do in a class context? The ones I already know of are __init__, __enter__, __next__, __exit__, __iter__, __str__, __repr__, and __call__. Or is this pretty much a complete list, except for a few?

I've been scratching my head about this for a while now (mostly because I don't know what to call these functions so I can't really research them).

Upvotes: 0

Views: 73

Answers (1)

Blckknght
Blckknght

Reputation: 104722

Since there's no answer to this reasonable question, I'll summarize the suggestions given in the comments as a community wiki.

The official Python documentation mostly calls methods like __init__ and __iter__ "special methods." It has a list of them in its chapter on the Python data model.

Python programmers often uses the less formal term "magic methods". Or, since the names are surrounded by double-underscores, the term "dunder method" may make sense, especially when you're going to need to be speaking their names out loud (you can say "dunder init" as a simple and clear way to express the name __init__ without tying your tongue in knots, an approach popularized by Ned Batchelder).

It's worth noting that some objects have special attributes that are not actually methods. For example, functions and modules have a __name__ attribute that is a string. (The module's __name__ is usable as a global variable within the module, and you'll often see used that way in if __name__ == "__main__" boilerplate.) All objects should have a __class__ attribute (which is a reference to their type), and many will have a __dict__ attribute (a dictionary) as well.

Upvotes: 1

Related Questions