327 midterm
composition*
"has-a" relationship a car has 4 wheels ownership is important car OWNs 4 wheels (wheels cannot be alone) filled in diamond on side of thing that has them (car) number of each (1 car to 4 wheels)
boundary values
89 90 are boundary values for grading function
which of following is true A child class must re-implement the parent's methods. Child classes are more general than their parents. A child class can use attributes defined in the parent class.
A child class can use attributes defined in the parent class.
diamond problem
A subclass inheriting from two superclasses, both of which unknowingly inherit from a single supersuperclass MRO solves this by when you inherit from multiple classes, if their method names conflict, the first one named takes precedence
All exceptions in Python inherit from this class.
BaseException
encapsulation*
Combining data and methods in a class
duck typing
Duck typing is the act of determining if an object is of the correct "type" by simply checking if it has attributes or methods of the right names. "If it looks like a duck and quacks like a duck, then it must be a duck." runtime error if method not defined (EAFP) easier to ask forgiveness than permission as opposed to LBYL look before you leap
After an exception is handled, the program will continue running following the line that initially raised the exception.
F
If a method calls super() it must be the first line in that method.
F
If you define a class called Event in event.py, you can import this class in another file with the line import event.Event
F
In python, all data attributes must be defined in the __init__ method. T/F
F
floats are a good way to store variables representing money.
F
The concept of Polymorphism describes the ability to modify public data attributes. T/F
FALSE
information hiding
Hiding all details of an object that do not contribute to its essential characters hiding details that other objects do not care about
How can I recognize that a function is an instance method?
It takes self as its first argument
widget variables
SringVar, IntVar, DoubleVar, BooleanVar etc. attach widgets using variable or textvariable attribute
A static method in ExampleClass cannot access instance variables for objects of ExampleClass. T/F
T
Abstract methods are meant to be overriden.
T
If an exception is never handled, then the program will terminate.
T
The method with the header below is implemented for MyClass. This defines the behavior of < when used to compare instances of MyClass.def __lt__(self, other):
T
When using multiple except clauses, they should be ordered from most specific to most general.
T
We talked briefly about a type of diagram to show classes and objects. What is the 3 letter abbreviation for these?
UML
try except block
When you think an error may occur, you can write a try-except block to handle the exception that might be raised. The try block tells Python to try running some code, and the except block tells Python what to do if the code results in a particular kind of error.
polymorphism
ability to treat a class differently depending on which subclass is implemented a subclass can override a method of the base class
event-driven programming
almost all GUIs are event-driven one main loop, listens for events, triggers callback functions
instance
an orange is an instance of Class fruit
symbolic execution
analyze code to determine what inputs leads to different paths in the control flow graph
How many classes can you inherit from in Python?
any number
why use OOP
approachable design technique flexibility, reusability, abstraction how replaceable the components or modules of a system are
Python docstrings for methods should appear...
at the top of a method definition under the header
public interface
attributes and methods used to interact with an object from the outside only what is necessary while hte rest remains hidden (careful with design / chaning)
object-oriented design/modeling tips
break problem into pieces ask what are the objects involved and how do they interact
logging
caught an exception to keep the program running but still want to see what it was
multiple inheritance
class MyCLass(ClassA, ClassB...) get all the attribute sand behaviors of both best to avoid conflicts?
class vs instance
class Student: _ schoolName = 'XYZ School' # protected class attribute def __init__(self, name, age): self._name=name # protected instance attribute self._age=age # protected instance attribute
abstract classes
class not meant to be instantiated directly template for other classes defines the public interface tpyically doesnt implement methods, requires subclasses to
object
collection of data AND behaviors
Choose the option that indicates the stronger relationship between objects.
composition
In the Notebook example, the most accurate relationship between Notes and Notebook is...
composition
What relationship would exist between a chess board and the spaces on the board?
composition
logging rankings
critical error warning info debug CEWID
data no behaviors
data structures like list, set, dict
adding parameters to parent class
def __init__(self, new_parameter, *args, **kwargs): self.foo = new_parameter super().__init__(*args, **kwargs) lecture4
types of relationships from weakest to strongest*
dependency association aggregation composition inheritance DAACI
docstrings
document purpose and behavior of objects and methods describes the public interface if someone else wants to reuse your code what do they need to know
magic methods
dunder methods + operatior is same as using the __add__() metod num + 5 num.__add__(5) is same usually used to define overoaded behaviors of predefined operators in python
contexxt managers
enters a local context with setup and cleanup handled automatically with object as name uses magic methods to enter/exit object.__enter__() object . __exit() locking/unlocking resources open/closing files
What is wrong with the following code? try: s = input("Please enter an integer: ") n = int(s) except Exception: print("%s is not an integer." % s)
except handles more errors than are described by print statement
UML sequence diagram
explains how objects are communicating half arrows: messages sent to /from an object solid arrows: method calls dashed arrows: method return values time goes as we move down
getters / setters
expose private parts of an object to the public interface better than using instance variables directly
code coverage by weakest to strongest
funciton statement branch edge condition FSBEC
functions as objects
functions can be passed around, modified any object can act like a funciton by making it callable foo(arg1, arg2) foo.__call__(arg1, arg2)
aggregation*
has a relationship if object can exist on own, then aggregation (more general than composition) NOT filled diamond with number 1 or if many *
Java
has abstract classes and interfaces no multiple inheritance, interfaces are more restricted can implement more than one interface has super but cant skip a level
condition coverage
has each boolean sub-expression evaluated both to true and false
branch coverage
has each branch of each control structure been executed
function coverage
has each funciton been called
statement coverage
has each statement in the program been executed
edge coverage
has every edge in the cotrol flow graph been executed
manager objects
high level objects that manage other object morer abstract than other objects
child class inherits
instance variables instance methods
white box testing
internal structure is known unit testing / integration testing
inheritance*
is a relationship more specific version of an object
Which of the following languages does not support multiple inheritance? Java/Python/C++
java
fuzzing
large-sale randomized input testing instead of worrying about right boundary values, just try everything
tkinter
main used widget toolkit/GUI framework attach callback functions to objects representing elements in a window
In a UML sequence diagram, the arrows indicate...
method calls
monkey patching
methods are attributes and can be changed during runtime objects as function
class (vs instance vs static)
methods take cls arg variables attached to the class instead of an instance each instance can access the class variables
instance (vs class vs static)
methods take self as arg variable is attached to a particular instance of a class each instance has separate copies of the variable
unit test mocking
monkey patching lets us change methods at runtime fkae the behavior of some code to make tests simpler and more independent
static (vs instance vs class)
not associated with any class or instance
Which of these options allows you to access the following mangled name from outside its class? class MyClass: def __init__(self): self.__secret = 10 obj1 = MyClass()
obj1._MyClass__secret
exceptions
objects or classes in a try... except block, exceptions matched based on inheritance
super()
often needed in init but can be used elsewhere can be anywhere in a method same as super(CurrentCLass, self)
dependency*
one object "uses" another object - - - - - - > driver uses a map
python "properties"
only use getters/setters when needed convenience of dot notation access name = property(getter, setter, deleter, docstring) getter, setter etc. are all defined functions in the class that do what their name says
Based on the code above, which is the proper way to change the name of the paper color? getters / setters Class Color: name = property(_get_name, _set_name) paper_color = Color("#FFC0CB", "pink")
paper_color.name = "lightish red"
other programming paradigms
procedural C) imperative along with OOP funcitonal (racket) and logic [delarative]
OOP
programming paradigm software is built as a collection of objects that interact with each other
class
prototype for an object that defines a set of attributes that characterize any object of the class
association*
relationships between objects a straight line that has number / * depending on how many there are ie. siblings, family
control flow graph
shows all possible paths for the function
C++
similar to python no abstract classes / interfaces supports multiple inheritance no super
mixin
specifc use case for multiple inheritance add features to multiple other classes could also do composition
behavior no data
static functions
integration testing
test interaction between smaller components often needs consistent dev environment
unit testing
test the smallest possible pieces independently
unittest framework
testclass extends /inherits from unittest.TestCase each test is a method in that class with a name starting with test_ calls assertion methods like self.assertRaises(etc setUp method run autometically before each test tearDown method run automatically after each test
method resolution order
the order in which methods should be inherited in the presence of multiple inheritance.
Multiple inheritance causes problems when...
the parent classes share the same methods or attributes.
object relational mapper
translates high-level objects into database tables / queries/transactions python has SQLAlchemy
public attributes and methods
usable from code outside the instance accessible from outside the class object is required to invoke public method std.age public attribute ex class Student: schoolname = XYZ std = Student("Steve") std.schoolName >XYZ
protected
usable within a class or by subclasses single underscore can use @property decorators init: self._name = name #protected instance attribute _schoolName #protected class attribute
private attributes and methods
usable within an instance no direct access from other objects double underscore python does not explicitly enforce public/private
abstraction*
use of a complex object without knowledge of its details user only able to view basic functionalities whereas the internal details are hidden
UML (unified modeling language)
well-defined language useful for object relationships
mutable defaults
when passing a mutable value as a default argument, the default argument is mutated anytime that value is mutated mutable: lists [] and sets and dictionaries
test-driven development
write tests first estables how the cod ewill be used
black box testing
you dont have the code and are just testing inputs and outputs without knowing what is going on inside internal structure/design is unknown