Magic Methods Flashcards
__new__(cls, *args, **kwargs)
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
__init__(self, *args, **kwargs)
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
__del__(self)
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
__repr__(self)
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
__str__(self)
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
__bytes__(self)
Called by bytes() to compute a byte-string representation of an object, returning a bytes object
__format__(self, format_spec)
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)
The so-called “rich comparison” methods
\_\_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
__hash__(self)
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)
__bool__(self)
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
__getattr__(self, name)
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
__getattribute__(self, name)
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)
__setattr__(self, name, value)
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
__delattr__(self, name)
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
__dir__(self)
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.