Mod 6 Flashcards

1
Q

How are classes and objects related(4)?

A
  • A class is a set of objects.
  • An object belongs to a class.
    -An object is an incarnation of the requirements, traits and qualities assigned to a class.
  • Classes do not need an object to exist
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Compare subclass vs superclass

A

Subclasses are more specialized, superclass is more general.

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

What is inheritance as it relates to superclass/subclass?

A

Passing attributes and methods from the superclass (defined and existing) to a newly created class, called the subclass.

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

What is an object comprised of(3)?

A
  • name that uniquely defines it (noun - car)
  • set of individual attributes (adjective - red)
  • set of abilities to perform specific actives (verb - drive)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Write the code to create a class and object:

A

class SampleClass:
pass

SampleObject = SampleClass()

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

What is instantiation?

A

An object being created and becoming an instance of the class.

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

Cons of the procedural approach (the stack)(2):

A
  • The stack list or variable is highly vulnerable, anyone can modify it in a uncontrolled manner
  • if you want multiple stacks, cannot easily duplicate them, confusing code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Benefits of the object oriented approach (the stack)(2):

A
  • Can encapsulate values so they can be neither accessed nor modified
  • do not need to duplicate code to create multiple stacks
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a constructor? What is its purpose? What is the constructors name?

A
  • A function that is invoked implicitly and automatically.
  • Its purpose is to construct a new object.
  • The name is __init__.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the parameter that must be used with __init__

A

self
example
class SampleClass:
def __init__(self):
print(“Hola!”)

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

Explain the below code:
class Stack:
def __init__(self):
self.stackList = []

A

The “Stack” class has a constructor so that objects can be made. The “stackList” property has been added to the new object, it is ready to use its value.

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

What do two underscores signify before a class component name? Where can this be accessed? What is this called?

A

The class component becomes private. It can be accessed only from within the class. This is encapsulation.

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

When functions are created, why must a parameter named “self” be present?

A
  • It allows the method to access the object’s entities
  • A method it needs to have least one parameter, which is used by Python
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Write the code to create two stacks:
class Stack:
def __init__(self):
self.__stackList = []

def push(self, val):
    self.\_\_stackList.append(val)

def pop(self):
    val = self.\_\_stackList[-1]
    del self.\_\_stackList[-1]
    return val
A

stackObject1 = Stack()
stackObject2 = Stack()
- Two stacks created from the same base class, they work independently.

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

Based upon the below code, how are Stack and AddingStack related?

class Stack:
pass

class AddingStack(Stack):
pass

A

Stack is the superclass while AddingStack is the subclass. AddingStack gets all the components defined by its superclass.

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

What does the Stack.__init__(self) line do below?
class Stack:
def __init__(self):
self.__stackList = []

def push(self, val):
    self.\_\_stackList.append(val)

def pop(self):
    val = self.\_\_stackList[-1]
    del self.\_\_stackList[-1]
    return val

class AddingStack(Stack):
def __init__(self):
Stack.__init__(self)
self.__sum = 0

A

It explicitly invokes the superclass’s constructor. Otherwise the class wouldn’t have the __stackList property.

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

True or False:
Invoking any method from inside the class never requires you to put the self argument at the arguments list

A

False
Invoking any method from OUTSIDE the class never requires you to put the self argument at the argument’s list

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

What are instance variables?

A
  • They are variables created at the object level.
  • They can possess different set of properties.
  • They can be created within the constructor.
  • Modifying an instance variable has no impact on all the remaining objects.
  • These only exist when there is no object in the class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What instance variables to the objects below contain:
class ExampleClass:
def __init__(self, val = 1):
self.first = val

def setSecond(self, val):
    self.second = val

exampleObject1 = ExampleClass()
exampleObject2 = ExampleClass(2)

exampleObject2.setSecond(3)

exampleObject3 = ExampleClass(4)
exampleObject3.third = 5

A

exampleObject1 has the first variable
example Object 2 has the first and second variables
example Object 3 has the first and third variables

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

What is the __dict__ variable?

A
  • Returns a dictionary
  • It contains all of the names and values of all the properties (variables) the object is currently carrying.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Info about Class Variables. Where is it stored? Does it exist even when there are no objects?

A
  • It’s stored outside any object.
  • A class variable exists in one copy even if there are no objects in the class.
  • They always show the same value in all class instances
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

True or False:
The __dict__ is empty if the object has no instance variables

A

True

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

What does the hasattr function do? What are its arguments? What does it return?

A
  • Checks if any object/class contains a specified property (variable).
  • It needs two arguments, the class or object and the name of the property.
  • It returns True or False
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the output of:
class ExampleClass:
a = 1
def ExampleClass():
def __init__(self):
self.b = 2

exampleObject = ExampleClass()

print(hasattr(exampleObject, ‘b’))
print(hasattr(exampleObject, ‘a’))
print(hasattr(ExampleClass, ‘b’))
print(hasattr(ExampleClass, ‘a’))

A

True
True
False
True

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

What is a method? Is a parameter required? Convention?

A
  • It is a function embedded inside a class
  • must have at least one parameter
  • convention is to use “self” as the parameter
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Facts about “self” parameter(2):

A
  • Gain access to an object’s instance and class variables
  • Used to invoke other object/class methods from inside the class
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Facts about the constructor(3):
Parameter (2)?

A
  • it is obliged to have the self parameter
  • doesn’t need to have more parameters
  • can be used to set up the object
  • cannot return a value
  • cannot be invoked directly either from the object or from inside the class
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Write the code to access the hidden method name “__hidden”:
class Classy:
def visible(self):
print(“visible”)

def \_\_hidden(self):
    print("hidden")

obj = Classy()

A

obj._Classy__hidden()

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

What does the __name__ property (variable) do?

A

It contains the name of the class. It exists only inside classes.

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

What does the type() function do (in the context of classes/objects)?

A

It will find the class of a particular object.

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

Write the code that will return the name of the class:
class Classy:
pass

A

print(Classy.__name__)

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

Write the code that will return the name of the class:
class Classy:
pass
obj = Classy()

A

print(type(obj).__name__)

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

What does the __module__ attribute do?

A

It stores the name of the module which contains the definition of the class

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

What does the __bases__ attribute do?

A

It is a tuple that contains a list of all the classes the given class inherits. Only classes have this attribute. A class without explicit superclasses points to “object”.

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

What is introspection?

A

the ability of a program to examine the type or properties of an object at runtime

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

What is reflection?

A

the ability of a program to manipulate the values, properties and/or functions of an object at runtime.

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

True or False:
Reflection and introspection enable a programmer to do anything with every object, no matter where it comes from.

A

True

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

What does the __str__() function do?

A

It returns a string. Helpful for when the class/object output needs to be a string.

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

What is the name and syntax of the function that is able to identify the relationship between two classes? What does it return?

A

issubclass(ClassOne, ClassTwo)
- it returns True if ClassOne is a subclass of ClassTwo and False otherwise
Note: each class is considered to be a subclass of itself

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

What is the name and syntax of the function that is able to identify the relationship between a object and class? What does it return?

A

isinstance(ObjectName, ClassName)
- it returns True if the object is an instance of the class, False otherwise
Note: being an instance of a class or one of its superclasses

41
Q

What is the output of:
class Vehicle:
pass

class LandVehicle(Vehicle):
pass

class TrackedVehicle(LandVehicle):
pass

myVehicle = Vehicle()
myLandVehicle = LandVehicle()
myTrackedVehicle = TrackedVehicle()

for obj in [myVehicle, myLandVehicle, myTrackedVehicle]:
for cls in [Vehicle, LandVehicle, TrackedVehicle]:
print(isinstance(obj, cls), end=”\t”)
print()

A

True False False
True True False
True True True

42
Q

What does the “is” operator do?

A

It checks whether two variables refer to the same object.

43
Q

What is the output of:
str1 = “Mary had a little “
str2 = “Mary had a little lamb”
str1 += “lamb”

print(str1 == str2, str1 is str2)

A

True False

44
Q

What does the super() function do?

A

It accesses the superclass without needing to know its name.

45
Q

Write the code to access the superclass and any entity in it(2):

A

super().__init__()
Super.__init__(self)
Note: “Super” is used assuming that is the superclass name

46
Q

What is the output of:
class Super:
def __init__(self):
self.supVar = 11

class Sub(Super):
def __init__(self):
super().__init__()
self.subVar = 12

obj = Sub()

print(obj.subVar)
print(obj.supVar)

A

12
11

47
Q

Describe Python’s behavior when searching for properties and methods for single inheritance

A

Python looks:
- in the object itself
- in all classes involved in the objects inheritance line from bottom to top
- if the above fails, an exception (Attribute Error) is raised

48
Q

What is it called when a class has more than one superclass?

A

Multiple inheritance

49
Q

Describe Python’s behavior when searching for properties and methods for multiple inheritance

A

Python looks:
- inside the class itself
- in its superclasses from bottom to top
- if there is 1+ class on a particular inheritance path, Python scans them from left to right

50
Q

class Left:
var = “L”
varLeft = “LL”
def fun(self):
return “Left”

class Right:
var = “R”
varRight = “RR”
def fun(self):
return “Right”

class Sub(Right, Left):
pass

obj = Sub()

print(obj.var, obj.varLeft, obj.varRight, obj.fun())

A

R LL RR Right

51
Q

What is polymorphism?

A

When the subclass modifies its superclass behavior. Each classes behavior may be modified at any time by any of its subclasses. It helps to keep code clean and consistent

52
Q

What is the output of:
class One:
def doit(self):
print(“doit from One”)

def doanything(self):
    self.doit()

class Two(One):
def doit(self):
print(“doit from Two”)

one = One()
two = Two()

one.doanything()
two.doanything()

A

doit from One
doit from Two

53
Q

What is composition?

A

process of composing an object using other different objects. It is a container able to store and use other objects where each of the objects implements a part of a desired class’s behavior.

54
Q

Pro of Single and Cons of Multiple Inheritance:

A
  • Single is simpler, safe and easier to understand
  • Mult is risky, able to easy make mistakes
  • Mult may make overriding difficult
  • Mult violates the single responsibility principle
  • Mult should be used as a last resort
55
Q

How are “else:” branches treated in “try: except:” statements? Name two rules.

A
  • the else block is only executed when no exception has been raised inside the try: statement.
  • In a try statement only one branch can be executed (except or else).
  • the else branch must be located after the last except branch
56
Q

How are finally branches treated in try: except: statements?

A

The finally block is always executed.

57
Q

What is the output of:
def reciprocal(n):
try:
n = 1 / n
except ZeroDivisionError:
print(“Division failed”)
n = None
else:
print(“Everything went fine”)
finally:
print(“It’s time to say goodbye”)
return n

print(reciprocal(2))
print(reciprocal(0))

A

Everything went fine
It’s time to say good bye
0.5
Division failed
It’s time to say good bye
None

58
Q

What is the purpose of the last 2 lines:
try:
i = int(“Hello!”)
except Exception as e:
print(e)
print(e.__str__())

A

They allow the user to see the reason for the raised exception.

59
Q

True or False:
Exceptions are objects

A

False.
Exceptions are classes.

60
Q

What does the printExcTree() function do and what is its syntax?

A

it shows the built-in exceptions.
print(excTree(exception name, nesting level)

61
Q

What is the args property?

A

It’s a tuple designed to gather all arguments passed to the class constructor.

62
Q

What is the output of:
def printargs(args):
lng = len(args)
if lng == 0:
print(“”)
elif lng == 1:
print(args[0])
else:
print(str(args))

try:
raise Exception
except Exception as e:
print(e, e.__str__(), sep=’ : ‘ ,end=’ : ‘)
printargs(e.args)

try:
raise Exception(“my exception”)
except Exception as e:
print(e, e.__str__(), sep=’ : ‘, end=’ : ‘)
printargs(e.args)

try:
raise Exception(“my”, “exception”)
except Exception as e:
print(e, e.__str__(), sep=’ : ‘, end=’ : ‘)
printargs(e.args)

A

: :
my exception : my exception : my exception
(‘my’, ‘exception’) : (‘my’, ‘exception’) : (‘my’, ‘exception’)

63
Q

True or False:
Users can create their own exceptions

A

True
Users can do as subclasses derived from predefined ones

64
Q

What is a generator? What else are they called? What function is often an example of one?

A
  • code able to produce a series of values
  • also controls the iteration process.
  • referred to as iterators
  • range() function is an example.
65
Q

What is the iterator protocol?

A
  • rules imposed by for and in statements
  • the way the object conforms to said rules
66
Q

An iterator must provide what to methods?

A

__iter__()
__next__()

67
Q

What does the __iter__() method do?

A

it returns the object itself and is invoked once

68
Q

What does the __next__() method do?

A

it returns the next value. If there are no more values to provide it should raise the StopIteration exception

69
Q

True or False - the function below is a generator:
def fun(n):
for i in range(n):
return i
print(fun(3))

A

False - the output is 0

70
Q

What does the yield statement do?
def fun(n):
for i in range(n):
yield i

print(fun(5))

A

It turns the function into a generator. It should be not invoked explicitly because its a generator object (and not a function). It will return the objects identifier. Must add this to make it return the value series.
for v in fun(5):
print(v)

71
Q

What is the output of:
def powersOf2(n):
pow = 1
for i in range(n):
yield pow
pow *= 2

for v in powersOf2(4):
print(v)

A

1
2
4
8

72
Q

What is the output of:
lst = []

for x in range(10):
lst.append(1 if x % 2 == 0 else 0)

print(lst)

A

[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]

73
Q

Which one is a generator? Which is a list comprehension?
a = [1 if x % 2 == 0 else 0 for x in range(10)]
b = (1 if x % 2 == 0 else 0 for x in range(10))

A

a is a list comprehension
b is a generator

74
Q

What does the lambda function do?
What is its syntax?

A

It returns the value of the expression when taking into account the current value of the current lambda argument
lambda parameters : expression

75
Q

What is the output of:
two = lambda : 2
sqr = lambda x : x * x
pwr = lambda x, y : x ** y

for a in range(-2, 3):
print(sqr(a), end=” “)
print(pwr(a, two()))

A

4 4
1 1
0 0
1 1
4 4

76
Q

What is the map() function? And what is the syntax?

A

applies the function passed by its first argument to all its second arguments elements and returns an iterator delivering all subsequent function results.
map(function, list)

77
Q

What is the output of:
list1 = [x for x in range(5)]
list2 = list(map(lambda x: 2 ** x, list1))
print(list2)

A

[1, 2, 4, 8, 16]

78
Q

What is the filter() function? What happens to the elements that return True? False?

A

It filters its second argument while being guided by directions flowing from the function specified as the first argument. The elements which return True pass the filter, all others are rejected.

79
Q

What is a closure?

A

It is a technique which allows the storing of values in spite of the fact that the context in which they have been created does not exist anymore. They must be invoked the same way in which it has been declared.

80
Q

True or False: the below are all acceptable Window’s file paths:
name = “\dir\file”
name = “/dir/file”

A

True

81
Q

What is it called when connecting to a stream and disconnecting?

A

Opening the file (open statement) and closing the file (close statement).

82
Q

What is the difference between read, write and update modes?

A

When a stream is opened in:
- read mode it allows read operations only
- write mode it allows write operations only
- trying to read the stream in write mode (or vice versa) will cause an UnsupportedOperation error
-update mode allows read and write operations

83
Q

How are binary streams read/written?

A

Byte by byte or block by block

84
Q

How are text streams read/written?

A

Character by character or line by line

85
Q

What do r, w, a, r+, w+, t and b mean? For each mode, does the stream need to exist? What happens if it does exist?

A

they are all modes that a stream can be opened in
r - read mode, the stream must exist
w - write mode, the stream doesn’t need to exist (if it doesn’t, it is created). If it exists, the data is truncated.
a - append mode, the stream doesn’t need to exist (if it doesn’t, it is created). If it exists, new data is appended.
r+ - read and write allowed, the stream must exist and has to be writeable.
w+ - write and read allowed, the stream doesn’t need to exist (if it doesn’t, it is created). If it exists, the data is truncated. Read and write operations permitted.
t - text mode
b - binary mode

86
Q

What are the three streams that are “pre-opened” in python? How do you import them?

A

sys.stdin (standard input) - normally associated to the keyboard
sys.stdout (standard output) - normally associated with the screen.
sys.stderr (standard error) - normally associated with the screen
the difference between the last to is that stdout provides useful results, stderr provides error messages

87
Q

Write the code for using a try/except statement and IOError for catching stream exceptions:

A

try:
#stream operation
except IOError as exc:
print(exc.errno)

88
Q

What is the strerror() function?

A

It simplifies the error handling code, it expects just one argument, the error number. It receives the error number and returns a description of the error.

89
Q

Write a sample code of how to use the strerror() function:

A

from os import strerror
try:
s = open(“c:/users/user/Desktop/file.txt”, “rt”)
# actual processing goes here
s.close()
except Exception as exc:
print(“The file could not be opened:”, strerror(exc.errno));

90
Q

What does the read() function do?

A

Reads the desired number of characters and returns them as a string. It can read the whole file or if there is nothing to read in the file it will return an empty string.

91
Q

What does the readline() function do?

A

Reads the file’s contents as a set of lines.

92
Q

What does the readlines() function do?

A

Reads all the file contents, and returns a list of strings, one element per file line. You can restrict it to read a specified number of bytes. The argument is the maximum accepted buffer size.

93
Q

True or False: The 5th line is illegal
from os import strerror

try:
ccnt = lcnt = 0
for line in open(‘text.txt’, ‘rt’):
lcnt += 1
for ch in line:
print(ch, end=’’)
ccnt += 1
print(“\n\nCharacters in file:”, ccnt)
print(“Lines in file: “, lcnt)
except IOError as e:
print(“I/O error occurred: “, strerr(e.errno))

A

False - the __next__ method allows the open() function to be iterable. Also, the object automatically invokes close() when the end of the file is reached.

94
Q

What does the write() function do?

A

It writes to a file. The argument takes in text. Writing a file in read mode will cause an error.

95
Q

What is a bytearray?

A

Its an array containing amorphus bytes. Amorphous data is data which has no specific shape or form, they are just series of bytes.

96
Q

Facts about bytearrays(3)

A
  • mutable
  • cannot set any byte array element with a value which is not an integer
  • also not allowed to assign a value that doesn’t come from the range 0 to 255 inclusive
97
Q

What is the readinto() function?

A

Allows users to read from a binary file and fills a previously created byte array object.

98
Q

What is the alternative function to read the contents of a binary file into memory?

A

read()
the argument specifics the max number of bytes to be read.