classes Flashcards

memorize details about python classes

1
Q

super()

A

super(class, instance) -> returns object up the MRO list with its attributes and methods

  1. Basic: Allows you to call a method on a base class within the overridden method on a subclass
  2. Complicated: returns an actual object with attributes and methods based on where it was used.
  3. Appears to go backward through the MRO to find a method or attribute in the case of complex inheritances.
  4. Typically, ‘class’ is the class where it was used, and instance is ‘self’
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

isinstance()

issubclass()

A

isinstance(instance, class)

  • determines if an instance of a class has the stated class anywhere in its inheritance chain

issubclass(class, class)

  • determines if an actual class inherits from another class

always True:

isinstance(obj, cls) == issubclass(type(obj), cls)

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

class dunders

A
  • __bases__
  • __subclasses__()
  • __mro__ # new style classes only
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How a class is created

A

a class is a code block, will accept any valid python code.

  1. When a new class is found, python makes a namespace for the block
  2. assignments are made to the new namespace
  3. the namespace is used to populate a new type object, representing the class

the new type has 3 things

  1. the name of the class
  2. the base classes
  3. the namespace dictionary

Identical:

class Example(int):

spam = 'eggs'

Example = type(‘Example’, (int,), {‘spam’:’eggs’})

Calling type directly is troublesome and doesn’t appear worth it

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

Metaclasses

  • a class to create classes
A

done by subclassing ‘type’ and overriding any methods necessary, usually __new__() or __init__()

type takes three arguments, so will __init__()

class SimpleMetaClass(type):

def \_\_init\_\_(cls, name, bases, attrs):

    print(name)

    super(SimpleMetaClass, cls).\_\_init\_\_(name, bases, attrs)

This will print out the name of every class it encounters.

class Example(metaclass=SimpleMetaClass):

pass

declaring this class (not creating an instance)

will produce:

Example

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

Plugin Framework

A

Used as applications get large. Accomodates flexibilitiy. Things are needed.

  1. define a place where plugins can be used.
  2. Should be obvious how to implement individual plugins
  3. Framework needs to provide a way to access the found plugins

So, they should extend a base class - the point where plugins are plugged in.

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

What’s a plugin look like?

A

makes a place for the class inheriting this to mount plugins, if it already has one, mounts the plugin on its parent class.

class PluginMount(type):
‘’’
Place this metaclass on any standard Python class to turn it into a plugin mount point. All subclasses will be automatically registered as plugins.
‘’’
def __init__(cls, name, bases, attrs):
if not hasattr(cls, ‘plugins’):
cls.plugins = []
else:
cls.plugins.append(cls)

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

Controlling the namespace

A
  • use __prepare__ method on a metaclass
  • rather than getting the namespace dictionary as an argument, it is responsible for returning that dictionary.
  • often used with an ordered dictionary so attributes can be stored in the order they were declared
  • @classmethod
  • __prepare__(cls, name, bases): return OrderedDict()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Attribute methods

A
  1. getattr() retrieves the value of an attribute
  2. setattr() sets it
  3. delattr() deletes it

These can be used to access attributes without knowing their names.

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

Properties

A

Properties allow attributes to be powered by methods that can use python logic

use the “@property” decorator

It forces the function to be called whenever the attributes name is accessed as an attribute

(why not just use a method?)

class Person:
   def \_\_init\_\_(self, first, last):
     self.first = first
     self.last = last
   @property   
   def name(self):
     return '%s, %s' % (self.last, self.first)

To add a setter, you need a method of the same name (name, in this case), decorated by @name.setter

@name.deleter does what’s expected

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

Descriptors

p 129

A

Problem with properties is that they require all methods to be defined as part of the class definition.

Allows definition of an object to behave like a property, regardless of the class it’s assigned on. Basically assigns a class to an attribute.

both methods and properties are just descriptors behind the scenes

This example always returns the current time. __get__ provides an up-to-date value.

class CurrentTime:

def __get__(self, instance, owner):

return datetime.datetime.now()

class Example:

time=CurrentTime()

__set__() works similarly, but can only be performed on instances. (maybe create a list and log events and times, etc).

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

Methods

A

Unbound

when accessing a function on a class, it is an unbound method - doesn’t need an instance

Callable like any other function, but it carries some class info with it.

Bound

Backed by the same function, but the method now recieves the instance as its first argument

**since bound methods accept an instance as the first argument, method binding can be faked by explicitly passing an instance to an unbound method. Handy when passing functions around as callbacks.

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

Class Methods

p 134

A

using @classmethod decorator, passes class as first argument to the method, even if the method was called on an instance.

Any method decorated like this will have the class passed as its first argument, including all subclasses.

it is bound, since the method is bound on the class it was called from.

You can also define the method in a metaclass. The class will be the first argument. The method will not be available on instances of classes that inherit form the metaclass, but the class will have the method.

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

Static Methods

p134

A

For when the class is more information than is necessary for the method to do its job. the @staticmethod decorator ensures the method won’t receive any implicit arguments at any time.

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

Assigning functions to classes and instances

A

works how you’d expect I think. assign an arbitrary function to a class attribute and that class can execute the new function - if it requires an argument the class can’t execute it, if it doesn’t, it works just like a static method.

A function assigned to an instance attribute works just like a static method as well.

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

__init__() and __new__()

A
  1. __new__() - first arg is actually the class, not the instance. Receives all arguments given when creating the object
  2. __init__() - makes the object after new decides what to do

consider a class that randomly chooses which subclass to be whenever it’s instantiated

import random

class Example:

def __new__(cls, *args, **kwargs):

cls = random.choice(cls.__subclasses())

return super(Example, cls).__new__(cls, *args, **kwargs)

17
Q

Automatic Subclasses

A

Rather than have users decide which of many classes to use, make a class that takes given data and returns an appropriate class.

import random

class Example:

def __new__(cls, *args,**kwargs):

cls = random.choice(cls.__subclasses__())

return super(Example, cls).__new__(cls, *args, **kwargs)

Now, when example is called, one of it’s subclasses will be randomly chosen.

18
Q

Dealing with Attributes

A

Defining __getattr__(self, name) will make Python call it whenever you request an attribute that hasn’t been defined.

just reiterates attribute methods

__setattr__(self, name, value)

__delattr__(self, name)

19
Q

__str__()

__unicode__()

__repr__()

A

define the method to ge a readable string representation of the object.

As of 3.0, all __str__ methods return unicode, I think. They used to be expected to return a bytestring while __unicode__() returned unicode.