COMP 110 - QZ 04

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/35

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

36 Terms

1
New cards

What does self refer to in Python Classes?

refers to the current instance of the class that the methods will operate on if those methods are called in the future on an instance of that class

2
New cards

Similar to how a function is first defined then called, a class is first defined then ____.

Instantiated

3
New cards

How is a class instatiatied?

my an object calls upon it
Ex: my_object = Class(value)

4
New cards

A class is first defined then ____.

instantiated

5
New cards

When a method is called, do you have to pass an argument to the self parameter?

No - When you call the constructor for a class, self is automatically made by python in order for the rest of the constructor to finish making the object. In the case of other methods, python knows that self is the object that you called the method on, often the variable name that comes before the method call (e.g. for my_point.shift_y(1.0), self is my_point).

6
New cards

When is self used outside of a class definition.

Never - Outside of a class definition you use the name of the variable storing an object to refer to it.
ex: self.x = x

7
New cards

What is “\n“?

It is a newline character. It is used to indicate a line break in strings or when printing output.

print("Hello\World")

#Output:
Hello
World

8
New cards

What properties of a recursive function will ensure that it does not have an infinite loop?

  • recursive case progresses towards the base case

  • base case returns a result directly (it does not call the function again)

  • the base case is always reached

9
New cards

A linked list in python consists of one or more instances of the _____ class.

Node

10
New cards

T/F: Attempting to access the value or next attribute of None will result in an error.

knowt flashcard image

True, attempting to access any attributes of None will result in an error since it has no attributes.

11
New cards

T/F: There is no way to traverse to the start of a linked list that has multiple Nodes given only a reference to the last Node.

knowt flashcard image

True, Nodes only know about the Node “in front” of them, or the next Node, so you cannot move backwards in a linked list.

12
New cards

When creating a __str__ method, what do you generally want to return? How is this different than what the __repr__method returns?

The __str__ returns a human-readable string that represents the object, usually including its attributes.

The __repr__ method returns a string representation as well, but for the python interpreter and for debugging purposes. Generally the string you create is made to look like a call to the constructor that would construct the object you are representing.

13
New cards

T/F: In order to call a magic method, you use its name (e.g. __str__) directly just like any other method.

False! It is almost always implicitly called such as in the previous question, or such as when the __init__ method is called using the class name.

14
New cards

Would the line of code that creates my_str also call the Point class’s __str__ method?

knowt flashcard image

Yes it would! In order to create a str object that includes my_point like this in the f-string, the __str__ method of my_point is implicitly called.

15
New cards

What is a magic method?

a function you define that python already has built-in functionality for (ex: __init__)

16
New cards

What is __str__?

A magic method that produces a human-readable string representation of an object.

Its primary goal is clarity and conciseness, making it suitable for display to end-users or for logging information where readability is paramount. It is invoked by the built-in str() function and implicitly by the print() function.

    class Book:
        def __init__(self, title, author):
            self.title = title
            self.author = author

        def __str__(self):
            return f"{self.title} by {self.author}"

    book = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams")

    print(book) # Calls book.__str__()
    # Output: The Hitchhiker's Guide to the Galaxy by Douglas Adams

17
New cards

What is __repr__?

A magic method that produces a string representation of an object, primarily for developers and debugging purposes. 

It is invoked by the built-in repr() function and when an object is evaluated in the interactive Python interpreter (e.g., typing the object's variable name). Generally the string you create is made to look like a call to the constructor that would construct the object you are representing.

    class Book:
        def __init__(self, title, author):
            self.title = title
            self.author = author

        def __repr__(self):
            return f"Book(title='{self.title}', author='{self.author}')"

    book = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams")

    print(repr(book)) # Calls book.__repr__()
    # Output: Book(title='The Hitchhiker\'s Guide to the Galaxy', author='Douglas Adams')

18
New cards

What does it mean to overload operatorss?

Operator overloading in Python allows same operator to work in different ways depending on data type.

When we use an operator on user-defined objects, Python doesn’t know how to handle it. To make operators work with custom classes, Python provides special methods (also called magic methods).

+ operator -> calls add(self, other)
- operator -> calls sub(self, other)
== operator -> calls eq(self, other)

So, when we write obj1 + obj2, internally Python calls:

obj1.__add__(obj2)

If this method is defined in the class, operator overloading works.

class A:
    def __init__(self, a):
        self.a = a

    # define behavior of +
    def __add__(self, o):
        return self.a + o.a 

ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")

print(ob1 + ob2)   # integer addition
print(ob3 + ob4)   # string concatenation

# actual working (internally)
print(A.__add__(ob1, ob2))
print(ob1.__add__(ob2))

19
New cards

What is the magic method for ‘+’?

__add__(self, other)

20
New cards

What is the magic method for ‘-’?

__sub__(self, other)

21
New cards

What is the magic method for ‘*’?

__mul__(self, other)

22
New cards

What is the magic method for ‘/’?

__truediv__(self, other)

23
New cards

What is the magic method for ‘**’?

__pow__(self, other)

24
New cards

What is the magic method for ‘%’?

__mod__(self, other)

25
New cards

What is the magic method for ‘<’?

__lt__(self, other)

26
New cards

What is the magic method for ‘>’?

__gt__(self, other)

27
New cards

What is the magic method for ‘<=’?

__le__(self, other)

28
New cards

What is the magic method for ‘>=’?

__ge__(self, other)

29
New cards

What is the magic method for ‘==’?

__eq__(self, other)

30
New cards

What is the magic method for ‘!=’?

__ne__(self, other)

31
New cards

What is recursion?

When a process (function) or structure (data type) is defined in terms of itself.

32
New cards

What is a recursive data type?

contains itself as an attribute/part of an attribute

(Class has an attribute that is its same type)

ex: linked lists

knowt flashcard image

33
New cards

What are the 2 components of recursion?

  1. base case

    • where recursion ends

    • often smallest inputs

    • prevent infinite loops

  2. recursive rule

    • def to handle all inputs that aren’t base case

    • expresses function in terms of smaller calls to the function 

34
New cards

What is a Node?

a recursive structure that makes up a linked list

35
New cards

What is a linked list?

  • made up of nodes

  • defined using Node class 

  • a linear data structure composed of a sequence of nodes, where each node contains data and a reference (or pointer) to the next node in the sequence

  • can’t point backwards

  • attributes are data and next

knowt flashcard image

36
New cards

What are the considerations for the base and recursive cases when “building“ a new linked list in a recursive function?

  • Base case:

    • does the function have a clear base case?

    • will the base case always be reached?

  • Recursive case:

    • determine what the 1st value of the new linked list will be

    • then “build” the rest of the list be recursively calling the building function

    • finally, return a new Node(first, rest) representing the new linked list