Object Oriented Programming Flashcards

1
Q

superclass <– subclass

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

How are objects and classes related?

A

A class (among other definitions) is a set of objects. An object is a being belonging to a class.

An object is an incarnation of the requirements, traits, and qualities assigned to a specific class.

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

What is inheritance?

A

Any object bound to a specific level of a class hierarchy inherits all the traits (as well as the requirements and qualities) defined inside any of the superclasses.

Inheritance is a common practice (in object programming) of 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 are the three attributes of an object?

A

an object has a name that uniquely identifies it within its home namespace (although there may be some anonymous objects, too)

an object has a set of individual properties which make it original, unique, or outstanding (although it’s possible that some objects may have no properties at all)

an object has a set of abilities to perform specific activities, able to change the object itself, or some of the other objects.

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

What is object programming?

A

the art of defining and expanding classes

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

What is instantiation?

A

The act of creating an object of the selected class is also called an instantiation (as the object becomes an instance of the class).

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

What is the alternative name for a stack?

A

LIFO
last in - first out

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

What is a stack?

A

A stack is a structure developed to store data in a very specific way.

A stack is an object with two elementary operations, conventionally named push (when a new element is put on the top) and pop (when an existing element is taken away from the top).

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

What is encapsulation?

A

the encapsulated values can be neither accessed nor modified if you want to use them exclusively;

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

What does the constructor do?

A

Construct a new object within a class

The constructor should know everything about the object’s structure, and must perform all the needed initializations.

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

What is the constructors name and parameter?

A

__init__(self)

It is invoked implicitly and automatically with he class

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

How do you access a property of the contructor?

A

self.name_property

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

How do you create a private class componenet?

A

two underscores before name __

it can only be accessed within the class and you cannot see it from the outside world (encapsulation)

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

All method within a class need….

A

The self parameter

It allows the method to access entities (properties and activities/methods) carried out by the actual object.

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

How do you define a subclass of a stack?

e.g. class Stack:

A

class SubStack(Stack):

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

Python forces you to explicitly invoke a superclass’s instructor. True or False

A

def __init__(self):
superclassname.__init__(self)

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

example of superclass and subclass

A

class Stack:
def __init__(self):
self.__stk = []

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

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

class CountingStack(Stack):
def __init__(self):
Stack.__init__(self)
self.__counter = 0

def get_counter(self):
    return self.\_\_counter

def pop(self):
    self.\_\_counter += 1
    return Stack.pop(self)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Describe an instance variable

A

If the value of a variable varies from object to object, then such variables are called instance variables. For every object, a separate copy of the instance variable will be created.

An instance variable is a property whose existence depends on the creation of an object. Every object can have a different set of instance variables.

Moreover, they can be freely added to and removed from objects during their lifetime. All object instance variables are stored inside a dedicated dictionary named __dict__, contained in every object separately.

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

What is a class variable?

A

A class variable is a property which exists in just one copy and is stored outside any object.

Two important conclusions:

class variables aren’t shown in an object’s __dict__ (this is natural as class variables aren’t parts of an object) but you can always try to look into the variable of the same name, but at the class level - we’ll show you this very soon;
a class variable always presents the same value in all class instances (objects)
- if the class is called three time and there is a counter the counter will be three for all printouts of the objects

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

What is mangling?

A

When you try and call a private variables you need to put _classname__varaible

class ExampleClass:
__counter = 0
def __init__(self, val = 1):
self.__first = val
ExampleClass.__counter += 1

example_object_1 = ExampleClass()

print(example_object_1.__dict__, example_object_1._ExampleClass__counter)

  1. An instance variable can be private when its name starts with __, but don’t forget that such a property is still accessible from outside the class using a mangled name constructed as _ClassName__PrivatePropertyName.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the difference between
class ExampleClass:
varia = 1
def __init__(self, val):
self.varia = val

and

class ExampleClass:
varia = 1
def __init__(self, val):
ExampleClass.varia = val

and

class ExampleClass:
varia = 1
def __init__(self, val):
varia = val

A

The first one creates an instance variable varia with the same name as the class variable

The second one only creates a class variables varia

The third does nothing it just operates on the methods local variable

22
Q

class ExampleClass:
def __init__(self, val):
if val % 2 != 0:
self.a = 1
else:
self.b = 1

example_object = ExampleClass(1)

print(example_object.a)
print(example_object.b)

Output?

A

1
Traceback (most recent call last):
File “.main.py”, line 11, in
print(example_object.b)
AttributeError: ‘ExampleClass’ object has no attribute ‘b’

23
Q

What does the function hasattr do?

A

Python provides a function which is able to safely check if any object/class contains a specified property. The function is named hasattr, and expects two arguments to be passed to it:

the class or the object being checked;
the name of the property whose existence has to be reported (note: it has to be a string containing the attribute name, not the name alone)
The function returns True or False.

24
Q

class ExampleClass:
a = 1
def __init__(self):
self.b = 2

example_object = ExampleClass()

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

Output?

A

True
True
False
True

25
Q

Which of the Python class properties are instance variables and which are class variables? Which of them are private?

class Python:
population = 1
victims = 0
def __init__(self):
self.length_ft = 3
self.__venomous = False

A

population and victims are class variables, while length and __venomous are instance variables (the latter is also private).

26
Q

Write an expression which checks if the version_2 object contains an instance property named constrictor (yes, constrictor!).

A

hasattr(version_2, ‘constrictor’)

27
Q

What is a method?

A

a method is a function embedded inside a class.

a method is obliged to have at least one parameter - self

The name self suggests the parameter’s purpose - it identifies the object for which the method is invoked.

28
Q

What is the self parameter used for?

A

The self parameter is used to obtain access to the object’s instance and class variables.

The self parameter is also used to invoke other object/class methods from inside the class.

29
Q

class Classy:
def other(self):
print(“other”)

def method(self):
    print("method")
    self.other()

obj = Classy()
obj.method()

A

method
other

30
Q

What can’t the instructor do?

A

Return a value, as it is designed to return a newly created object and nothing else;
cannot be invoked directly either from the object or from inside the class (you can invoke a constructor from any of the object’s subclasses, but we’ll discuss this issue later.)

31
Q

How do you get the name of a class form the class and from the object?

A

class Classy:
pass

print(Classy.__name__)
obj = Classy()
print(type(obj).__name__)

32
Q

What does __module__ do?

A

__module__ is a string, too - it stores the name of the module which contains the definition of the class

class Classy:
pass

print(Classy.__module__)
obj = Classy()
print(obj.__module__)

output =
__main__
__main__

any module named __main__ is actually not a module, but the file currently being run.

33
Q

What does __bases__ do?

A

__bases__ is a tuple. The tuple contains classes (not class names) which are direct superclasses for the class.

only classes have this attribute - objects don’t.

Note: a class without explicit superclasses points to object (a predefined Python class) as its direct ancestor.

34
Q

What is introspection?

A

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

35
Q

What is reflection?

A

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

36
Q

What method prints out a string in a class?

A

__str__()

class Star:
def __init__(self, name, galaxy):
self.name = name
self.galaxy = galaxy

def \_\_str\_\_(self):
    return self.name + ' in ' + self.galaxy

sun = Star(“Sun”, “Milky Way”)
print(sun)

37
Q

What function can identify a relationship between two classes?

A

issubclass(ClassOne, ClassTwo)

The function returns True if ClassOne is a subclass of ClassTwo, and False otherwise.

There is one important observation to make: each class is considered to be a subclass of itself. e.g. issubclass(classone,classone) = True

38
Q

What function can identify the relationship between an object and a class?

A

isinstance(objectName, ClassName)

The functions returns True if the object is an instance of the class, or False otherwise.

Being an instance of a class means that the object (the cake) has been prepared using a recipe contained in either the class or one of its superclasses.

39
Q

The is operator checks whether two variables (object_one and object_two here) refer to the same object.

A

object_one is object_two

Don’t forget that variables don’t store the objects themselves, but only the handles pointing to the internal Python memory.

40
Q

class SampleClass:
def __init__(self, val):
self.val = val

object_1 = SampleClass(0)
object_2 = SampleClass(2)
object_3 = object_1
object_3.val += 1

print(object_1 is object_2)
print(object_2 is object_3)
print(object_3 is object_1)
print(object_1.val, object_2.val, object_3.val)

string_1 = “Mary had a little “
string_2 = “Mary had a little lamb”
string_1 += “lamb”

print(string_1 == string_2, string_1 is string_2)

A

False
False
True
1 2 1
True False

The results prove that object_1 and object_3 are actually the same objects, while string_1 and string_2 aren’t, despite their contents being the same.

41
Q

What does the super() function do?

A

Accesses the super class within a subclass without having to know its name

42
Q

What is multiple inheritance?

A

Multiple inheritance occurs when a class has more than one superclass

class Sub(SuperA, SuperB):

43
Q

If a subclass inherits two variables with the same name from different super classes which overrides which?

A

The entity defined later (in the inheritance sense) overrides the same entity defined earlier.

Python looks for object components:
inside the object itself;
in its superclasses, from bottom to top;
in inheritance paths left to right

44
Q

What is polymorphism?

A

the situation in which the subclass is able to modify its superclass behaviour

The method, redefined in any of the superclasses, thus changing the behaviour of the superclass, is called virtual.

45
Q

What is composition?

A

Composition is the process of composing an object using other different objects. The objects used in the composition deliver a set of desired traits (properties and/or methods) so we can say that they act like blocks used to build a more complicated structure.

46
Q

What does MRO stand for?

A

Method Resolution Order

47
Q

When is the else branch executed in a try-except block?

A

the else branch is executed if no exception is raise in the try branch
it goes after the last except branch

48
Q

When is the finally branch executed in a try-except block?

A

The finally block is always executed (it finalizes the try-except block execution, hence its name), no matter what happened earlier, even when raising an exception, no matter whether this has been handled or not.

49
Q

try:
i = int(“Hello!”)
except Exception as e:
print(e)
print(e.__str__())

What does this do?

A

The example presents a very simple way of utilizing the received object - just print it out (as you can see, the output is produced by the object’s __str__() method) and it contains a brief message describing the reason.

50
Q

What does the property args do?

A

It’s a tuple designed to gather all arguments passed to the class constructor. It is empty if the construct has been invoked without any arguments, or contains just one element when the constructor gets one argument (we don’t count the self argument here), and so on.