Magic Methods Flashcards

1
Q

__new__(cls, *args, **kwargs)

A
Called to create a new instance of a class
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
  • Static method (special case that doesn’t need to be declared as such)
  • Takes the class as its first argument, the remaining arguments are those passed to the construction call
  • Invoked during obj creation
  • Returns an instance of the class, then the init method will be called where self is this new instance
  • If it doesn’t return an instance of the class, init is not called
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

__init__(self, *args, **kwargs)

A

Called after instance is created by __new__
_________________________________

  • Called after the instance has been created, but before it is returned to the caller
  • The arguments are those passed to the construction call
  • Shouldn’t return anything (ie return None)
  • Customizes the object
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

__del__(self)

A

Called when an instance is about to be destroyed
_________________________________

  • It is not guaranteed to call when interpreter exits
  • del x doesn’t directly call x.__del__()
    • the former decrements the reference count for x by one
    • the latter is only called when x’s reference count reaches zero
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

__repr__(self)

A

The “official” string representation of an object
_________________________________

  • Called by repr() (and in nested contexts)
  • The return value must be a str object
  • This should look like a valid Python expression that could be used to recreate an obj with the same value
  • If not possible, provide a useful, information-rich description
  • Used in informal contexts when __str__ is not provided
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

__str__(self)

A

The “informal” string representation of an object
_________________________________

  • Called by str(), format(), and print()
  • The return value must be a str object
  • Doesn’t expect to return a valid Python expression, can be convenient or concise representation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

__bytes__(self)

A

Called by bytes() to compute a byte-string representation of an object, returning a bytes object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

__format__(self, format_spec)

A

The “formatted” string representation of an object
_________________________________

  • Called by format(), formatted str literals and str.format()
  • The return value must be a str object
  • format_spec is a string containing description of the formatting options desired (according to mini formatting language)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

The so-called “rich comparison” methods

A
\_\_lt\_\_(self, other)
\_\_le\_\_(self, other)
\_\_eq\_\_(self, other)
\_\_ne\_\_(self, other)
\_\_gt\_\_(self, other)
\_\_ge\_\_(self, other)
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
  • For successful comparisons, False and True are returned
  • If it does not implement the operation for a given pair of arguments, it may return the singleton NotImplemented
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

__hash__(self)

A

Called by built-in hash() and for operations on members of hashed collections like set, frozen set, and dict
_________________________________

  • Should return an integer
  • The only required property is that objects which compare equal have the same hash value
  • It is advised to mix together the hash values of the components of the object that also play a part in comparison by packing them in a tuple and hashing the tuple:
def \_\_hash\_\_(self):
    return hash((self.name, self.nick, self.color))
  • If a class doesn’t define __eq__ it shouldn’t define __hash__
  • If defines __eq__ but not __hash__, can’t be used in washable collections
  • If a class defines mutable obj and implements an __eq__ method, should not implement __hash__ (because washable collections require immutable keys)
  • User defined classes have default eq and hash, all objects compare unequal and hash returns an appropriate value where if x == y implies x is y and hash(x) == hash(y)
  • Overriding eq but not hash implicitly sets hash to None
    • Raises TypeError when hash is attempted
  • If you don’t override eq but want to suppress hash, set __hash__ = None, not raise TypeError (will be erroneous on some calls)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

__bool__(self)

A

Called to implement truth value testing
_________________________________

  • Should return False or True
  • When undefined, __len__ is called
    • If it is defined, nonzero result evaluates as True
    • If neither is defined, evaluates as True
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

__getattr__(self, name)

A

Called when default attribute access fails with an AttributeError (when __getattribute__ or __get__ raises the exception)
_________________________________

  • Should return the attribute value or raise an AttributeError exception
  • If found through normal lookup, getattr is not called
  • Because it is only called when attribute is undefined, can fetch other attributes without recursion
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

__getattribute__(self, name)

A
Called unconditionally to implement attribute accesses for instances of the class
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
  • Should return the attribute value or raise an AttributeError exception
  • To fetch another attribute and avoid recursion, use superclass function object.__getattribute__(self, name)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

__setattr__(self, name, value)

A

Called when an attribute assignment is attempted
_________________________________

  • Called instead of normal mechanism of storing to the instance dict
  • To set an attribute and avoid recursion, use superclass function object.__setattr__(self, name, value)
  • You can also assign it to self.__dict__[name] = value
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

__delattr__(self, name)

A

Called when attribute deletion is attempted
_________________________________

  • Use if del name should be meaningful
  • Less often implemented, but requires similar superclass or dict functionality like setattr
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

__dir__(self)

A

Called when dir() is called on the object, returning a sequence
_________________________________

  • dir() converts the returned sequence to a sorted list.

dir([object]):
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

__get__(self, instance, owner=None)

A

Descriptor - only applies when an instance of the descriptor class (where this method is defined) is used as an attribute in the owner class (appears in the class dictionary for the class or its parents)

Called to get the attribute of the owner class (or an instance of the owner class)

17
Q

__set__(self, instance, value)

A

Descriptor - only applies when an instance of the descriptor class (where this method is defined) is used as an attribute in the owner class (appears in the class dictionary for the class or its parents)

Called to set the attribute on an instance of the owner class to a new value

18
Q

__delete__(self, instance)

A

Descriptor - only applies when an instance of the descriptor class (where this method is defined) is used as an attribute in the owner class (appears in the class dictionary for the class or its parents)

Called to delete the attribute on an instance of the owner class

19
Q

__set_name__(self, owner, name)

A

Descriptor - only applies when an instance of the descriptor class (where this method is defined) is used as an attribute in the owner class (appears in the class dictionary for the class or its parents)

Called at the time the owning class is created, assigning the attribute name to the descriptor
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
  • Called implicitly, so when adding a descriptor after initial creation, must be passed explicitly
20
Q

__slots__

A
Not a method, a class variable that allows us to explicitly declare data members (like properties) and deny the creation of \_\_dict\_\_ (space saved can be significant, as well as attribute lookup speed) and \_\_weakref\_\_
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
class MyClass:
    \_\_slots\_\_ = ['name', 'age']
    def \_\_init\_\_(self, name, age):
         self.name = name
         self. age = age
21
Q

__enter__(self)

A

Enter the runtime context related to this object

22
Q

__exit__(self, exc_type, exc_value, traceback)

A

Exit the runtime context related to this object
_________________________________

  • The parameters describe the exception that caused the context to be exited
  • If the context exits w/o exception, they’ll all be None
  • Can return True to suppress the exception, otherwise exception will be processed normally
  • Should not reraise the passed-in exception
23
Q

__len__(self)

A

Called to implement len()
_________________________________

  • Should return an integer >= 0 that is the length of the object
  • If __bool__ is undefined, truthfulness is determined as False when this method returns 0, and True if it returns any other length
    • If this method also not implemented, defaults to True
24
Q

__getitem__(self, key)

A

Called to implement evaluation of self[key] (indexing)
_________________________________

  • Is used for iteration context if iter/next are undefined
  • Special interpretation of negative indexes can be specified
  • For sequence types, should raise IndexError for values outside the set of indexes
  • For mapping types, if key is missing, should raise KeyError
  • This is for indexing, as opposed to __index__ which assumes object is an integer and returns one
25
Q

__setitem__(self, key, value)

A

Called to implement assignment of self[key] (indexing)
_________________________________

  • Only implement if object should be mutable
  • Same exceptions should be raised as getitem for improper values
    • IndexError if sequence type and immutable or out of
      bounds
    • KeyError if mapping type and immutable
26
Q

__delitem__(self, key)

A

Called to implement deletion of self[key] (indexing)

27
Q

__iter__(self)

A

This method is called when an iterator is required for a container
_________________________________

  • Should return a new iterator object that can iterate over all the objects in the container
  • For mappings, should iterate over the keys
28
Q

__reversed__(self)

A

Called by the reversed() built-in to implement reverse iteration
_________________________________

  • Should return a new iterator that iterates over all the objects in the container in reverse order
  • If not implemented, the built in will fall back on sequence protocol (using len and getitem) - only provide if you can implement a more efficient protocol
29
Q

__contains__(self, item)

A

Called to implement membership test operators
_________________________________

  • Should return True if item is in self, False otherwise
  • For sequence objects, considers values
  • For mapping objects, should just consider keys
  • For objects that don’t define contains, membership test falls back on iter and then getitem - only provide if you can implement a more efficient protocol
30
Q

__call__(self)

A

Called when the instance is called as a function