Mastering Python OO Flashcards

1
Q

Simple namespace

A

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__”

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

Property

A

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.

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

Creating immutable objects

A

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

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

Create immutable object as tuple subclass

A

Subclass tuple

override __new__

ie. return super().__new__(cls, (*args))

override __getattr__(self, name)

return self[{attr1: val, attr2: val,..}[name]]

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

Eagerly computed attributes

A

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.

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

__getattribute__

A

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.

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

Descriptors

A

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:

  1. Under hood, methods of class are implemented as descriptors
  2. The property() function is implemented by creating a data descriptor for the named attribute
  3. A class method or static method is a descriptor - applies to class instead of instance.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Features of abstract base classes

examples - 3

uses - 3

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

isinstance

A

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

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

Abstract Base Class Meta

ABCMeta

A

__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

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

Features of context manager

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Context manager factory

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

namedtuple

A

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.

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

deque

A

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.

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

ChainMap

A

Takes any number of dictionaries/maps and aggregates them. Values from earlier arguments take precedence over those with the same key in later arguments

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

Counter

A

from collections import Counter

freq = Counter(<some_iterator>)</some_iterator>

unique elements of <some_iterator> are keys, values are frequencies</some_iterator>

freq has methods like “most_common” etc.

It is actually a “bag” or “multiset”

This means they can be added and subtracted

bag1 = Counter(‘asdfaasdf’)

bag2 = Counter(‘gd;fjhkljsf’)

bag1 + bag2 # yeilds union w/counts

bag1 - bag2 # what you’d expect

17
Q
A