Mastering Python OO Flashcards
Simple namespace
Found in ‘types’ module
Same features as adding attributes and values to a class, without all the class related stuff.
import types
n = types.SimpleNameSpace()
n. attribute = ‘value’
etc. ..
doesn’t use internal “__dict__”
Property
Looks like an attribute. We can get, set, and delete it.
It is actually a method and can process objects rather than just fetch them
They cannot be added to an object easily, like attributes
use “property” function
or @property decorator.
After setting property, use @<propertyname>.getter/setter/deleter to process what happens when you get, set and delete the property</propertyname>
Processing with getters/setters/deleters goes from lazy evaluation (like a regular method) to eager evaluation, potentially saving time.
Creating immutable objects
uses __slots__ - turns off __dict__ feature and allows only methods/attributes named in slots
define __setattr__ to say that the object doesn’t allow assignment to attributes
in __init__, call super().__setattr(self, ‘attribute’, ‘value’) to handle the fact that this object doesn’t allow setting attributes
Something like this ensures “hash” returns a consistent value
Create immutable object as tuple subclass
Subclass tuple
override __new__
ie. return super().__new__(cls, (*args))
override __getattr__(self, name)
return self[{attr1: val, attr2: val,..}[name]]
Eagerly computed attributes
calling a method after every time an attribute is set that checks if enough attributes are set to compute the necessary attribute.
def __dir__(self):
return list(self.keys())
def _solve(self):
if is not None self.v1 and is not None self.v2:
self[‘v3’] = self.v1 * self.v2
etc.
Method that does the calculating must refer self[attr_name] to avoid a recursive call to __setattr__ when assigning to v3.
__getattribute__
Lower level than __getattr__
Default attempts to locate attribute in __dict__ or __slots__
can be used to restrict access
def __getattribute__(self, name):
if name.startswith(‘_’):
….do something.
Descriptors
A class that mediates attribute access. They are built inside a class at class definition time.
A descriptor class defines a combination of get, set and delete methods
An instance will be an attribute on the owner class
Check example from chapter 3 ipython notebook
Uses:
- Under hood, methods of class are implemented as descriptors
- The property() function is implemented by creating a data descriptor for the named attribute
- A class method or static method is a descriptor - applies to class instead of instance.
Features of abstract base classes
examples - 3
uses - 3
Features
- Abstract means they don’t contain all method definitions required to work completely
- Base means other classes will use it as a superclass
- Provides some definitions for method functions - more importantly, provides signatures for missing method functions
For example
- Useful for defining a consistent set of base classes for Python’s internal classes and our custom application classes
- Common, reusable abstractions to use for applications
- use them to support proper inspection of a class to determine what it does
Uses:
- as superclass
- within a method to determine if something is possible
- within a diagnostic message or exception to indicate why it won’t work
isinstance
Overuse indicates poor design
It’s better to ask forgiveness than permission
try:
”"”something you want a class to do”””
except <exception>:</exception>
”"”informative warning”””
raise the error
Abstract Base Class Meta
ABCMeta
__subclasshook__
Special method implemented in __new__ of ABCMeta that prevents a subclass from being created (by returning NotImplemented) if it doesn’t supply all the required methods of the Abstract Base Class
__instancecheck__
implements the isinstance buil-in
__issubclass__
implements issubclass built-in
Features of context manager
has __enter__ and __exit__ methods
Often used to make transient global changes and set them back when complete
__enter__
- accepts one argument, self
__exit__
- accepts four arguments
- self, exception type, exception value, traceback
- all have a value of None under normal circumstances
- Does one of two things with exception
- silences by passing some True value
- Allowing exception to return normal by returning None or some False value
Context manager factory
Returns an object from __enter__ method rather than self
__exit__ method is still called as normal on exiting
Clean up technique ( a lot like a try…except…finally block)
- updating a file means writing the updates to a new file
- Then deleting original renaming new file the original name
- if there is an error, rename copy .*“error” and close it
namedtuple
Creates new class definition from supplied arguments
BlackjackCard = namedtuple(‘BlackjackCard’, ‘rank,suit,hard,soft’)
condenses a class definition to a very short statement and makes an immutable object
A factory function might be a nice way to make a bunch of instances.
deque
double-ended queue
provides uniform performance for all entries in a list
Operations that insert or pop from beginning of list have overhead because the length is changed and each entries position is changed.
ChainMap
Takes any number of dictionaries/maps and aggregates them. Values from earlier arguments take precedence over those with the same key in later arguments