1. Home
  2. Explore
  3. Computer Science
  4. Object-Oriented Programming in Python

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Object-Oriented Programming in Python

  • 70Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Programming Paradigms

Which description best distinguishes procedural programming from object-oriented programming as presented in the lecture?

70 questions

  1. 1

    Which description best distinguishes procedural programming from object-oriented programming as presented in the lecture?

    1. A

      Procedural programming organizes work as step-by-step procedures, while object-oriented programming organizes related data and functionality into classes and objects.

    2. B

      Procedural programming requires functions to be anonymous, while object-oriented programming requires every function to have a name.

    3. C

      Procedural programming is available in Python, while object-oriented programming is available only in languages such as Java.

    4. D

      Procedural programming uses only numbers, while object-oriented programming uses only strings and collections.

    Correct answer
    A

    Procedural programming organizes work as step-by-step procedures, while object-oriented programming organizes related data and functionality into classes and objects.

    Explanation

    Procedural code typically proceeds through procedures or functions step by step. Object-oriented programming provides a way to bundle related data and behavior into named classes and their objects.

  2. 2

    What does the ability to pass functions around or use an anonymous function illustrate about Python?

    1. A

      Python has features associated with functional programming, even when a program is not written entirely in that paradigm.

    2. B

      Python functions can be passed around only when they are stored in dictionaries.

    3. C

      Python requires all programs to use functional programming instead of procedures.

    4. D

      Python automatically converts every function into a class method.

    Correct answer
    A

    Python has features associated with functional programming, even when a program is not written entirely in that paradigm.

    Explanation

    Passing functions around and using anonymous functions are examples of functional-programming features. Python allows multiple programming paradigms rather than requiring only one.

  3. 3

    Why can object-oriented programming become especially useful as a program grows?

    1. A

      It guarantees that a program will never contain errors, regardless of its design.

    2. B

      It can help organize increasingly complex programs by grouping related data and behavior together.

    3. C

      It makes every operation run faster by replacing Python's interpreter.

    4. D

      It eliminates the need for functions, variables, or other basic programming constructs.

    Correct answer
    B

    It can help organize increasingly complex programs by grouping related data and behavior together.

    Explanation

    The lecture presents object-oriented programming as a useful way to organize larger and more complicated programs, especially by keeping related functionality together.

  4. 4

    A program has many unrelated functions mixed with several functions that all manipulate student data. What design improvement best follows the lecture's reasoning?

    1. A

      Move every function into one large function so that the program has fewer definitions.

    2. B

      Replace every function with a global variable so that all code can access the student data.

    3. C

      Make every student-related function anonymous so that its purpose is less tied to its name.

    4. D

      Group student-related data and behavior in a student class to make the program's organization clearer.

    Correct answer
    D

    Group student-related data and behavior in a student class to make the program's organization clearer.

    Explanation

    Classes can encapsulate related data and functionality. Grouping student-related operations with the student class makes the organization more coherent as the program grows.

  5. 5

    What is meant by encapsulating student-related functionality in a student class?

    1. A

      Putting every function in the program inside the student class.

    2. B

      Converting student data into a string before storing it.

    3. C

      Keeping student data and operations related to students together in the class.

    4. D

      Encrypting student data so that no part of the program can read it.

    Correct answer
    C

    Keeping student data and operations related to students together in the class.

    Explanation

    Encapsulation here means bundling related data and functionality together. It does not mean that every function belongs in the class or that data is encrypted.

  6. 6

    Why might a standalone function that gathers a student's name and house be considered a design smell in a program centered on a student class?

    1. A

      It returns an object, and standalone functions cannot return objects.

    2. B

      Its responsibility is student-related, so leaving it outside the class separates related functionality.

    3. C

      It uses input, and classes are not allowed to use input.

    4. D

      It contains two prompts, and a function may prompt the user only once.

    Correct answer
    B

    Its responsibility is student-related, so leaving it outside the class separates related functionality.

    Explanation

    The lecture describes separated student-related functionality as a potential code smell. Moving that behavior into the student class keeps the related code together.

  7. 7

    Which statement best describes the relationship between Python and object-oriented programming?

    1. A

      Python requires every variable to be an instance of a class written by the programmer.

    2. B

      Python is fundamentally limited to object-oriented programming and does not support procedural code.

    3. C

      Python supports object-oriented programming but also allows programmers to solve problems using other paradigms.

    4. D

      Python supports object-oriented programming only when a program imports a special external library.

    Correct answer
    C

    Python supports object-oriented programming but also allows programmers to solve problems using other paradigms.

    Explanation

    Python provides flexibility: it supports object-oriented programming alongside procedural and functional features.

  8. 8

    What is a reasonable rule of thumb for using a class in the examples discussed?

    1. A

      A class should be used for every variable, even when no related data or behavior exists.

    2. B

      A class should be used only to represent objects that physically exist in the real world.

    3. C

      A class can be useful for representing a real-world or imagined entity and grouping its related data and behavior.

    4. D

      A class is useful only when its objects must be stored permanently on disk.

    Correct answer
    C

    A class can be useful for representing a real-world or imagined entity and grouping its related data and behavior.

    Explanation

    Classes often model real-world or fantasy-world entities, such as students or a Sorting Hat, and can group related data and functionality. This is a heuristic, not an absolute rule.

  9. 9

    A simple program works correctly without classes. What does the lecture suggest about whether it must be rewritten using object-oriented programming?

    1. A

      It must be rewritten because every correct Python program requires a custom class.

    2. B

      It should be rewritten only if the program uses integers or strings.

    3. C

      It must be rewritten because functions cannot be used in programs that contain classes.

    4. D

      It need not be rewritten; classes are another design tool that can be more useful as problems become more complex.

    Correct answer
    D

    It need not be rewritten; classes are another design tool that can be more useful as problems become more complex.

    Explanation

    The lecture emphasizes that a simpler solution can be perfectly valid. Object-oriented programming is another tool that can help organize more sophisticated programs.

  10. 10

    What is the purpose of the if __name__ == "__main__" guard in the student program?

    1. A

      It ensures that the file can be imported only once and that its variables are immutable.

    2. B

      It converts the file into a class whenever another program imports it.

    3. C

      It checks whether the user's name is the word main before accepting input.

    4. D

      It runs the main function when the file is run directly, while avoiding an automatic call when the file is imported.

    Correct answer
    D

    It runs the main function when the file is run directly, while avoiding an automatic call when the file is imported.

    Explanation

    The guard allows the program to call main when run from the command line, without blindly running it when the file is imported as a module.

  11. 11

    What does returning name, house from a Python function actually return?

    1. A

      Two independent return values that Python stores separately.

    2. B

      A list that can be changed after the function returns.

    3. C

      A dictionary whose keys are automatically named name and house.

    4. D

      A single tuple containing the name and house.

    Correct answer
    D

    A single tuple containing the name and house.

    Explanation

    The comma creates a tuple, so the function returns one value containing both elements. It does not implicitly create a dictionary or list.

  12. 12

    How can a caller assign the two elements returned in a tuple to separate variables?

    1. A

      Use sequence unpacking, such as name, house = get_student().

    2. B

      Use dictionary-key syntax, such as get_student()["name"] and get_student()["house"].

    3. C

      Call the function twice and assume each call returns a different element.

    4. D

      Use attribute syntax, such as get_student().name and get_student().house.

    Correct answer
    A

    Use sequence unpacking, such as name, house = get_student().

    Explanation

    Python can unpack a returned sequence into corresponding variables using commas on the left side of an assignment.

  13. 13

    Which property distinguishes a tuple from a list in the lecture's comparison?

    1. A

      A tuple is indexed by strings, whereas a list is indexed by numbers.

    2. B

      A tuple is a key-value mapping, whereas a list is a sequence.

    3. C

      A tuple can contain only strings, whereas a list can contain any values.

    4. D

      A tuple is immutable, whereas a list is mutable.

    Correct answer
    D

    A tuple is immutable, whereas a list is mutable.

    Explanation

    Both tuples and lists can hold collections of values, but the tuple's contents cannot be reassigned while a list's contents can be changed.

  14. 14

    What is a likely result of attempting student[1] = "Ravenclaw" when student is a tuple?

    1. A

      Python silently converts the tuple into a mutable list.

    2. B

      Python changes the first item because tuple indices start at one.

    3. C

      Python raises a type error because tuple items do not support assignment.

    4. D

      Python changes the second tuple item and leaves the other items unchanged.

    Correct answer
    C

    Python raises a type error because tuple items do not support assignment.

    Explanation

    Tuples are immutable, so assigning a new value to one of their indexed items raises an error rather than modifying the tuple.

  15. 15

    Why might a programmer choose a tuple rather than a list for a pair of values that should not change?

    1. A

      The tuple allows the values to be accessed by descriptive string keys.

    2. B

      The tuple is required whenever a function returns more than one value.

    3. C

      The tuple communicates that the collection is not intended to be modified, helping prevent accidental changes.

    4. D

      The tuple automatically validates that both values have the same type.

    Correct answer
    C

    The tuple communicates that the collection is not intended to be modified, helping prevent accidental changes.

    Explanation

    Using an immutable tuple can help prevent accidental changes when the values are not meant to change. Python does not require tuples for multiple returned values, but commas commonly create one.

  16. 16

    How do lists and tuples use square brackets in Python?

    1. A

      Square brackets are used only for lists and cannot be used with tuples.

    2. B

      Square brackets create a tuple, but parentheses must be used to index into it.

    3. C

      Square brackets create both lists and tuples, while parentheses index into both.

    4. D

      Square brackets create a list, and they are also used to index into either a list or a tuple.

    Correct answer
    D

    Square brackets create a list, and they are also used to index into either a list or a tuple.

    Explanation

    Square brackets are used to create lists and to access elements by index in both lists and tuples. Parentheses are a visual indicator for creating a tuple.

  17. 17

    How does indexing into a dictionary differ from indexing into a list or tuple?

    1. A

      A dictionary is accessed using attributes, while lists and tuples are accessed using function calls.

    2. B

      A dictionary is accessed using keys, while lists and tuples are accessed using numeric indices.

    3. C

      A dictionary is accessed using numeric indices, while lists and tuples are accessed using string keys.

    4. D

      A dictionary is accessed only by its values, while lists and tuples are accessed by their keys.

    Correct answer
    B

    A dictionary is accessed using keys, while lists and tuples are accessed using numeric indices.

    Explanation

    Lists and tuples use numeric positions such as 0 and 1; dictionaries use keys, such as the strings name and house.

  18. 18

    Why can a dictionary be clearer than a tuple for storing a student's name and house?

    1. A

      A dictionary automatically checks that the house is one of Hogwarts' four houses.

    2. B

      A dictionary stores values in alphabetical order, making numeric positions unnecessary.

    3. C

      Keys such as name and house describe the values, so a reader need not remember their numeric positions.

    4. D

      A dictionary guarantees that its values cannot be changed after creation.

    Correct answer
    C

    Keys such as name and house describe the values, so a reader need not remember their numeric positions.

    Explanation

    Dictionary keys provide semantic labels for values. This can be clearer than remembering that one position means name and another means house.

  19. 19

    Which statement correctly describes mutability among the three collections discussed?

    1. A

      Tuples and dictionaries are immutable, while lists are mutable.

    2. B

      Lists and tuples are mutable, while dictionaries are immutable.

    3. C

      Lists and dictionaries are mutable, while tuples are immutable.

    4. D

      Lists, tuples, and dictionaries are all immutable.

    Correct answer
    C

    Lists and dictionaries are mutable, while tuples are immutable.

    Explanation

    The lecture describes lists and dictionaries as mutable collections and tuples as immutable.

  20. 20

    What is the purpose of type(value) in the exploration shown in the lecture?

    1. A

      It can reveal the type or class of a value, such as int, str, list, or dict.

    2. B

      It converts any value into a string without changing its underlying type.

    3. C

      It creates a new class named after the value's contents.

    4. D

      It checks whether a value is valid for a particular class's initializer.

    Correct answer
    A

    It can reveal the type or class of a value, such as int, str, list, or dict.

    Explanation

    The type function can be used to inspect the type of a value. The examples show integers, strings, lists, and dictionaries as instances of their respective classes.

  21. 21

    What is a class in the lecture's blueprint analogy?

    1. A

      A collection that must contain only strings and numeric indices.

    2. B

      A function that can be called only from the command line.

    3. C

      A named blueprint or mold used to define a type of data and the structure or behavior of its objects.

    4. D

      A specific value stored in a variable after the program finishes running.

    Correct answer
    C

    A named blueprint or mold used to define a type of data and the structure or behavior of its objects.

    Explanation

    A class defines a custom data type and serves as a blueprint or mold from which objects can be created.

  22. 22

    What is an object in relation to a class?

    1. A

      A collection of class names stored in a dictionary.

    2. B

      The source-code file in which the class was first written.

    3. C

      A special method that runs before the class is defined.

    4. D

      A particular instance created from the class's definition or blueprint.

    Correct answer
    D

    A particular instance created from the class's definition or blueprint.

    Explanation

    An object is an instance, or instantiation, of a class. The class defines the type; the object is a specific realization of it.

  23. 23

    In the student example, what does student = Student() do?

    1. A

      It converts the class definition into a string and stores that string.

    2. B

      It defines a new class named student with a lowercase initial letter.

    3. C

      It calls the Student object's __str__ method to create a formatted name.

    4. D

      It calls the Student class to create a student object and assigns that object to the variable student.

    Correct answer
    D

    It calls the Student class to create a student object and assigns that object to the variable student.

    Explanation

    Calling the class name with parentheses creates an instance of that class. The resulting object is assigned to the variable on the left.

  24. 24

    How are attributes such as name and house accessed on the student object in the example?

    1. A

      With dot notation, such as student.name and student.house.

    2. B

      With numeric indexing, such as student[0] and student[1].

    3. C

      With dictionary-key syntax, such as student["name"] and student["house"].

    4. D

      With function-call syntax, such as student(name) and student(house).

    Correct answer
    A

    With dot notation, such as student.name and student.house.

    Explanation

    The example stores and accesses class attributes using dot notation, as in student.name and student.house.

  25. 25

    What is the role of the self parameter in an instance method?

    1. A

      It provides access to the current object so the method can read or set that object's attributes.

    2. B

      It stores the arguments passed by every other object of the same class.

    3. C

      It prevents the method from accessing any data outside the function.

    4. D

      It refers to the class's source file so the method can import its code.

    Correct answer
    A

    It provides access to the current object so the method can read or set that object's attributes.

    Explanation

    By convention, instance methods receive self, a reference to the current object. This lets a method access or update that object's attributes.

  26. 26

    Why does __init__ include self even though a call such as Student(name, house) passes only name and house explicitly?

    1. A

      The caller must secretly provide self as the first argument, but Python ignores it.

    2. B

      The Student class automatically converts name into self and house into an argument.

    3. C

      Python automatically supplies the new object's reference as self, in addition to the explicitly provided arguments.

    4. D

      self is a default value that replaces name if the user leaves it blank.

    Correct answer
    C

    Python automatically supplies the new object's reference as self, in addition to the explicitly provided arguments.

    Explanation

    Python automatically passes a reference to the current object to an instance method. Thus, self is present in the method signature but is not supplied explicitly in the class call.

  27. 27

    What is the primary purpose of the __init__ method described in the lecture?

    1. A

      To select a random object from a list of possible instances.

    2. B

      To initialize an object's contents after the object has been created.

    3. C

      To convert an object to a user-friendly string whenever it is printed.

    4. D

      To define the class's name and make it available to imported modules.

    Correct answer
    B

    To initialize an object's contents after the object has been created.

    Explanation

    The lecture distinguishes object creation from initialization: __new__ handles creation, while __init__ initializes the object's contents and is typically the method programmers define.

  28. 28

    What does the lecture mean by calling Student(name, house) a constructor call?

    1. A

      It calls a function that prints the student's name and house but creates no object.

    2. B

      It unpacks a tuple into two separate student objects.

    3. C

      It invokes the class to create and initialize a student object using the supplied arguments.

    4. D

      It modifies the class definition so that every student has the same name and house.

    Correct answer
    C

    It invokes the class to create and initialize a student object using the supplied arguments.

    Explanation

    The class call creates an instance and uses the supplied values to customize it. The lecture refers to this as constructing or instantiating an object.

  29. 29

    What is the technical distinction between __new__ and __init__ noted in the lecture?

    1. A

      They are two names for the same method, and Python calls them interchangeably.

    2. B

      __init__ creates the class, while __new__ prints the object as a string.

    3. C

      __new__ validates user input, while __init__ catches all exceptions automatically.

    4. D

      __new__ creates the object, while __init__ initializes its contents; programmers generally focus on __init__.

    Correct answer
    D

    __new__ creates the object, while __init__ initializes its contents; programmers generally focus on __init__.

    Explanation

    The lecture states that __new__ handles creation of an empty object in memory, while __init__ initializes it. Programmers generally need not manipulate __new__.

  30. 30

    Why is self.name = name used inside __init__?

    1. A

      It changes the local variable name into a global variable shared by every object.

    2. B

      It stores the incoming name argument as an attribute of the current object.

    3. C

      It asks Python to look up a dictionary key named name on the current object.

    4. D

      It renames the class so that its name matches the user's input.

    Correct answer
    B

    It stores the incoming name argument as an attribute of the current object.

    Explanation

    The assignment creates or sets an instance attribute called name on the object referenced by self, using the method's name argument as its value.

  31. 31

    Which statement about the attributes created in the student example is supported by the lecture?

    1. A

      They are dictionary keys that can be accessed only with square brackets.

    2. B

      They must be integers because Python classes cannot store strings.

    3. C

      They are class variables automatically shared by every student object, and they must be strings.

    4. D

      They are instance variables belonging to a particular student object, and their values can be various data types.

    Correct answer
    D

    They are instance variables belonging to a particular student object, and their values can be various data types.

    Explanation

    The lecture calls object-specific attributes instance variables. The example uses strings, but it notes that an attribute's value could be another data type.

  32. 32

    What is a method in the lecture's terminology?

    1. A

      A variable stored only outside every class.

    2. B

      A function defined inside a class.

    3. C

      A special kind of tuple that can hold named keys.

    4. D

      A particular instance created from a class.

    Correct answer
    B

    A function defined inside a class.

    Explanation

    A method is a function inside a class. Some methods are special methods called automatically by Python; others are defined by the programmer.

  33. 33

    What does a class's __str__ method control?

    1. A

      The number of arguments accepted by every method in the class.

    2. B

      The validation rules applied when the object is first created.

    3. C

      The object's memory address and the location at which Python stores its class definition.

    4. D

      The string representation returned when an object is converted to a string, such as when it is printed.

    Correct answer
    D

    The string representation returned when an object is converted to a string, such as when it is printed.

    Explanation

    Defining __str__ lets a programmer customize how an object appears as a string. Without it, printing may show a default representation that includes the object's type and memory-related information.

  34. 34

    Why does an instance's __str__ method receive self when print(student) causes it to be called?

    1. A

      The print function passes the object's name as a string and Python converts it into self.

    2. B

      The method uses self to locate the class's source file before printing it.

    3. C

      Python automatically passes a reference to the object being converted, allowing the method to use its attributes.

    4. D

      The programmer must pass self to print explicitly after the student object.

    Correct answer
    C

    Python automatically passes a reference to the object being converted, allowing the method to use its attributes.

    Explanation

    Python calls __str__ when a string representation is needed and supplies a reference to the current object. The method can then use attributes such as the name and house.

  35. 35

    How does the lecture distinguish __str__ from __repr__?

    1. A

      __str__ is a class method, while __repr__ is a property setter.

    2. B

      __str__ is used only for numbers, while __repr__ is used only for dictionaries.

    3. C

      __str__ is generally intended to be user-friendly, while __repr__ is generally intended for developers and may include more information.

    4. D

      __str__ initializes an object, while __repr__ creates it in memory.

    Correct answer
    C

    __str__ is generally intended to be user-friendly, while __repr__ is generally intended for developers and may include more information.

    Explanation

    The lecture describes __str__ as generally user-facing and __repr__ as generally more useful to developers, potentially including the object's type and other details.

  36. 36

    Why might a class validate a student's name and house in its __init__ method?

    1. A

      It ensures Python will never allow any later changes to the object's attributes.

    2. B

      It can reject invalid data when a student object is being initialized, keeping student-related rules with the class.

    3. C

      It prevents the user from importing the student class into another program.

    4. D

      It automatically turns both values into immutable tuples.

    Correct answer
    B

    It can reject invalid data when a student object is being initialized, keeping student-related rules with the class.

    Explanation

    Putting validation in the student class keeps rules about valid student data with the class and can prevent creation of an object with invalid initial values.

  37. 37

    What is the role of raise ValueError("missing name") in the validation example?

    1. A

      It prints a warning and then guarantees that the program continues normally.

    2. B

      It exits the entire program immediately without allowing exception handling.

    3. C

      It signals an invalid value by raising an exception with an explanatory message.

    4. D

      It returns None before the student object has been created.

    Correct answer
    C

    It signals an invalid value by raising an exception with an explanatory message.

    Explanation

    The raise keyword lets a programmer signal an exception. A message such as missing name helps explain what went wrong; code may catch the exception with try and except.

  38. 38

    Why does the lecture prefer raising an exception over calling sys.exit when invalid data is encountered?

    1. A

      Raising an exception automatically fixes the invalid input and continues with a valid object.

    2. B

      Raising an exception signals the problem without necessarily forcing the entire program to terminate immediately.

    3. C

      sys.exit can be used only inside a class, while exceptions can be used only outside classes.

    4. D

      sys.exit converts invalid values into strings, while exceptions convert them into integers.

    Correct answer
    B

    Raising an exception signals the problem without necessarily forcing the entire program to terminate immediately.

    Explanation

    The lecture argues that exiting the whole program can be an extreme response. Raising an exception lets the calling code decide how to handle the error.

  39. 39

    If a student's house must be one of four recognized values, which validation condition matches the lecture's approach?

    1. A

      Replace every unrecognized house with the first item in the list without notifying the caller.

    2. B

      Store any supplied house and rely on the __str__ method to correct it later.

    3. C

      Raise a ValueError if the supplied house is not in the list of valid houses.

    4. D

      Reject the input only if it is a string rather than an integer.

    Correct answer
    C

    Raise a ValueError if the supplied house is not in the list of valid houses.

    Explanation

    The example checks whether the house belongs to a list containing Gryffindor, Hufflepuff, Ravenclaw, and Slytherin, and raises a ValueError otherwise.

  40. 40

    Why might a class provide a getter and setter for a property?

    1. A

      They allow code to control how an attribute is retrieved or changed, including validating assigned values.

    2. B

      They convert every attribute into a class variable shared by all objects.

    3. C

      They make the attribute impossible to read or change from any part of the program.

    4. D

      They allow Python to infer the attribute's value without storing it.

    Correct answer
    A

    They allow code to control how an attribute is retrieved or changed, including validating assigned values.

    Explanation

    A property getter and setter provide control over access and assignment. In the example, the setter checks a house value before storing it.

  41. 41

    What does the @property decorator do in the house example?

    1. A

      It makes the house value a class variable.

    2. B

      It defines a setter so any assignment to the property bypasses validation.

    3. C

      It defines a getter so the method can be accessed using property-style syntax such as student.house.

    4. D

      It converts the house attribute into a dictionary key.

    Correct answer
    C

    It defines a getter so the method can be accessed using property-style syntax such as student.house.

    Explanation

    The @property decorator marks a method as the getter for a property, allowing it to be read using attribute-style syntax.

  42. 42

    How is a setter associated with a property named house?

    1. A

      Define a class method named house that takes the class and no other arguments.

    2. B

      Define a method decorated with @house.setter, using self and the new house value as parameters.

    3. C

      Define a method decorated with @property.setter, using only the new house value as a parameter.

    4. D

      Define a function named set_house outside the class and call it automatically from print.

    Correct answer
    B

    Define a method decorated with @house.setter, using self and the new house value as parameters.

    Explanation

    The lecture uses @house.setter for the setter of the house property. The setter receives self and the value being assigned.

  43. 43

    Why does the example store the house value in self._house rather than self.house inside the getter and setter?

    1. A

      The underscore-prefixed instance variable avoids colliding with the property named house.

    2. B

      Python requires all properties to store values in variables that start with underscores.

    3. C

      The underscore converts the house into an immutable class variable.

    4. D

      Using self.house would make the getter return the student's name instead.

    Correct answer
    A

    The underscore-prefixed instance variable avoids colliding with the property named house.

    Explanation

    The property itself is named house, so using the same name for the underlying instance variable would collide. The conventional solution is to store the value in _house.

  44. 44

    Why does assigning self.house = house in __init__ help centralize validation?

    1. A

      Because self.house always refers directly to _house and cannot call a method.

    2. B

      Because assignment through the property invokes its setter, so initialization can use the same validation as later changes.

    3. C

      Because the assignment changes the property into a tuple before validation occurs.

    4. D

      Because Python skips the setter during initialization but invokes it when printing the object.

    Correct answer
    B

    Because assignment through the property invokes its setter, so initialization can use the same validation as later changes.

    Explanation

    The example deliberately assigns through self.house in __init__, causing the setter to run. This avoids duplicating the same house-validation logic in multiple places.

  45. 45

    What does a single leading underscore in a Python instance-variable name conventionally communicate?

    1. A

      The variable is fully private and Python will reject any access from outside its class.

    2. B

      The variable is intended for internal use and other programmers should avoid changing it, though Python does not strictly prevent access.

    3. C

      The variable is shared among every instance of the class.

    4. D

      The variable can be read but can never be assigned.

    Correct answer
    B

    The variable is intended for internal use and other programmers should avoid changing it, though Python does not strictly prevent access.

    Explanation

    The lecture describes underscore-based privacy as an honor-system convention in Python: it signals that a variable should not be touched, but does not strictly prevent access.

  46. 46

    What is a key limitation of property-based validation in Python, according to the lecture?

    1. A

      A property setter can validate values only during printing, not during assignment.

    2. B

      A programmer can still deliberately access the underscore-prefixed instance variable directly, bypassing the property.

    3. C

      A property cannot be used with strings such as student names or houses.

    4. D

      A property makes every assigned value immutable after the first assignment.

    Correct answer
    B

    A programmer can still deliberately access the underscore-prefixed instance variable directly, bypassing the property.

    Explanation

    Python relies on conventions rather than strict privacy enforcement in this example. Someone can still directly modify _house, even though they are not supposed to.

  47. 47

    What does a method decorated with @classmethod receive by convention?

    1. A

      The return value of the class's __str__ method.

    2. B

      A dictionary containing every instance variable of every object.

    3. C

      A reference to the current object, always named self, rather than the class.

    4. D

      A reference to the class, commonly named cls, rather than a reference to a particular instance.

    Correct answer
    D

    A reference to the class, commonly named cls, rather than a reference to a particular instance.

    Explanation

    A class method receives the class itself as its first argument, conventionally named cls. An ordinary instance method receives the current object as self.

  48. 48

    When is a class method appropriate in the Sorting Hat example?

    1. A

      When the method needs to convert each hat object into a user-facing string.

    2. B

      When the sorting behavior belongs to the Sorting Hat class and does not depend on a particular hat object.

    3. C

      When a method needs to initialize every object created from the class.

    4. D

      When the behavior must read a different private attribute from each hat instance.

    Correct answer
    B

    When the sorting behavior belongs to the Sorting Hat class and does not depend on a particular hat object.

    Explanation

    The example has one conceptual Sorting Hat and does not need separate hat objects. A class method can provide behavior associated with the class itself.

  49. 49

    What is a class variable?

    1. A

      A value that can be accessed only after a class is imported from a package.

    2. B

      A variable defined on the class itself and shared as a class-level value rather than stored separately on each instance.

    3. C

      A local variable created only while an instance method is running.

    4. D

      A variable automatically passed as self to every method.

    Correct answer
    B

    A variable defined on the class itself and shared as a class-level value rather than stored separately on each instance.

    Explanation

    Class variables belong to the class itself. The Sorting Hat example stores its list of houses as a class variable so class-level behavior can use it.

  50. 50

    Why can the Sorting Hat's list of houses be a class variable rather than an instance variable?

    1. A

      Each individual house needs a separate Sorting Hat object to store its name.

    2. B

      The list is shared information for the Sorting Hat class and does not need a separate copy for each hat object.

    3. C

      The list must be a class variable because Python cannot store lists on objects.

    4. D

      A class variable makes the list immutable, which is required for random selection.

    Correct answer
    B

    The list is shared information for the Sorting Hat class and does not need a separate copy for each hat object.

    Explanation

    The example uses one shared list of possible houses for the Sorting Hat's behavior, so storing it on the class avoids tying it to a particular hat instance.

  51. 51

    How does the sort method select a house in the Sorting Hat example?

    1. A

      It uses type to determine the student's class and then selects a fixed house.

    2. B

      It calls input to ask the student to choose a house and stores the response in a tuple.

    3. C

      It uses random.choice on the list of houses, after importing the random module.

    4. D

      It uses the __add__ method to combine the four house names.

    Correct answer
    C

    It uses random.choice on the list of houses, after importing the random module.

    Explanation

    The example imports random and uses random.choice on the available houses to select one randomly.

  52. 52

    Why can Hat.sort("Harry") work after sort is made a class method?

    1. A

      The method can be called through the class without first creating a Hat instance.

    2. B

      The method is actually a static method and receives no arguments of any kind.

    3. C

      The class name is converted into an instance when the argument is a string.

    4. D

      The class call automatically creates four Hat objects, one for each house.

    Correct answer
    A

    The method can be called through the class without first creating a Hat instance.

    Explanation

    A class method is callable through the class itself, so the example can use Hat.sort("Harry") without instantiating a hat.

  53. 53

    What does the cls parameter allow a class method to do in the Sorting Hat example?

    1. A

      Refer to a specific hat object and access its instance variable, such as self.houses.

    2. B

      Refer to the class and access its class variable, such as cls.houses.

    3. C

      Refer to the current user's input without receiving it as an argument.

    4. D

      Create an exception without using the raise keyword.

    Correct answer
    B

    Refer to the class and access its class variable, such as cls.houses.

    Explanation

    The class method receives the class through cls, allowing it to access class-level data such as cls.houses.

  54. 54

    Why was Student.get() designed as a class method in the revised student program?

    1. A

      It allows the method to print a student without receiving any information.

    2. B

      It can gather input and create a student without requiring an existing student object first.

    3. C

      It ensures that every student shares the same name and house.

    4. D

      It prevents the student class from having an initializer.

    Correct answer
    B

    It can gather input and create a student without requiring an existing student object first.

    Explanation

    Using a class method avoids a chicken-and-egg problem: the program can call Student.get() to obtain a student without first needing a student object.

  55. 55

    What does return cls(name, house) do inside a class method of Student?

    1. A

      It changes the class's name and house variables for every instance.

    2. B

      It creates and returns an instance of the class represented by cls, initialized with the supplied values.

    3. C

      It returns the class definition itself without creating an object.

    4. D

      It calls the class's __str__ method and returns the formatted string.

    Correct answer
    B

    It creates and returns an instance of the class represented by cls, initialized with the supplied values.

    Explanation

    cls refers to the class, so calling cls(name, house) creates an instance of that class using the given arguments and returns it.

  56. 56

    Which statement correctly distinguishes instance methods from class methods?

    1. A

      Instance methods must use a decorator; class methods never use decorators.

    2. B

      Instance methods operate with access to a particular object through self; class methods receive the class through cls.

    3. C

      Instance methods receive the class through cls; class methods receive a particular object through self.

    4. D

      Instance methods cannot access attributes; class methods can access only local variables.

    Correct answer
    B

    Instance methods operate with access to a particular object through self; class methods receive the class through cls.

    Explanation

    The lecture distinguishes methods by what their first argument represents: self is a particular object, while cls is the class. Instance methods are the default when no class-method decorator is used.

  57. 57

    What is inheritance in object-oriented programming?

    1. A

      A relationship in which a class can inherit attributes and methods from another class.

    2. B

      A method for making a tuple mutable after it has been created.

    3. C

      A rule that every class must inherit from two parent classes.

    4. D

      A process that converts an object into a string when it is printed.

    Correct answer
    A

    A relationship in which a class can inherit attributes and methods from another class.

    Explanation

    Inheritance lets a class reuse functionality from another class. The lecture describes a subclass as inheriting from a superclass.

  58. 58

    In the Wizard example, if Student inherits from Wizard, which class is the superclass?

    1. A

      Wizard is the superclass, and Student is its subclass.

    2. B

      Student is the superclass, and Wizard is its subclass.

    3. C

      Neither is a superclass because they each have an __init__ method.

    4. D

      Both are superclasses because they are defined in the same file.

    Correct answer
    A

    Wizard is the superclass, and Student is its subclass.

    Explanation

    The class named in the inheritance declaration, Wizard, is the parent or superclass; Student is the subclass that inherits from it.

  59. 59

    Why introduce a shared Wizard class for both students and professors in the example?

    1. A

      Python requires all classes with different initializers to inherit from a third class.

    2. B

      They share functionality such as having a name, so that common behavior and validation can be written once.

    3. C

      It allows professors and students to become the same type of object.

    4. D

      They must share a house and subject, so those values can be stored as one class variable.

    Correct answer
    B

    They share functionality such as having a name, so that common behavior and validation can be written once.

    Explanation

    Students and professors both have a name. A shared superclass can hold that common attribute and its validation, reducing duplicated code.

  60. 60

    What does super().__init__(name) accomplish in a subclass initializer?

    1. A

      It calls the subclass initializer a second time with no arguments.

    2. B

      It calls the superclass's initializer so the inherited part of the object can be initialized.

    3. C

      It converts the name into a class variable shared by all subclasses.

    4. D

      It creates a new superclass object separate from the subclass object.

    Correct answer
    B

    It calls the superclass's initializer so the inherited part of the object can be initialized.

    Explanation

    super() provides access to the parent class, and calling its __init__ lets the superclass initialize its part of the subclass object.

  61. 61

    In the Wizard hierarchy, what can a Student class do after inheriting from Wizard and calling super().__init__(name)?

    1. A

      Make the student's name immutable by converting it into a tuple.

    2. B

      Avoid creating any student object because the superclass already exists.

    3. C

      Reuse the professor's subject field without defining a professor class.

    4. D

      Reuse the superclass's name handling while adding student-specific data such as a house.

    Correct answer
    D

    Reuse the superclass's name handling while adding student-specific data such as a house.

    Explanation

    The superclass handles shared name functionality, while the subclass can add its own attribute, such as a student's house.

  62. 62

    What happens to inherited functionality through a deeper inheritance hierarchy?

    1. A

      A subclass can inherit functionality from its parent and more distant ancestor classes as well.

    2. B

      A subclass inherits only class variables, not methods or instance behavior.

    3. C

      A subclass inherits only from the class immediately above it and never from more distant ancestors.

    4. D

      A subclass loses all inherited functionality when it defines its own initializer.

    Correct answer
    A

    A subclass can inherit functionality from its parent and more distant ancestor classes as well.

    Explanation

    The lecture explains that inherited functionality can come from not only the direct parent but also more distant ancestors in the hierarchy.

  63. 63

    Which statement about multiple inheritance is supported by the lecture?

    1. A

      Python forbids a class from inheriting from more than one parent.

    2. B

      A class can inherit from multiple parents only if they are defined in separate files.

    3. C

      Multiple inheritance is required whenever a class has two attributes.

    4. D

      Python has ways to inherit from multiple parents, though the demonstration uses a single inheritance path.

    Correct answer
    D

    Python has ways to inherit from multiple parents, though the demonstration uses a single inheritance path.

    Explanation

    The lecture notes that multiple-parent inheritance is possible, but keeps the example simple by using a single inheritance path.

  64. 64

    What is operator overloading?

    1. A

      Using an operator without defining any behavior for the objects involved.

    2. B

      Creating entirely new keyboard symbols that Python will recognize as operators.

    3. C

      Defining how a familiar operator, such as +, behaves for objects of a custom class.

    4. D

      Replacing every built-in operator with a function that accepts only strings.

    Correct answer
    C

    Defining how a familiar operator, such as +, behaves for objects of a custom class.

    Explanation

    Operator overloading lets a class define an interpretation for familiar operators, such as addition, when they are used with its objects.

  65. 65

    What does the __add__ method represent for a custom class?

    1. A

      The behavior invoked for every comparison operator, regardless of its symbol.

    2. B

      The behavior invoked whenever an object is printed, with no operands passed in.

    3. C

      The process of creating the class, with the class name passed as the only argument.

    4. D

      The behavior invoked for the + operator, with the left and right operands passed to the method.

    Correct answer
    D

    The behavior invoked for the + operator, with the left and right operands passed to the method.

    Explanation

    The lecture uses __add__ to implement +. Its first parameter corresponds to the left operand and its second parameter corresponds to the right operand.

  66. 66

    In the vault example, what do self and other represent inside __add__ when evaluating potter + weasley?

    1. A

      self represents the sum, and other represents the number of coins.

    2. B

      Both represent the class Vault, not either operand.

    3. C

      self represents the left vault, and other represents the right vault.

    4. D

      self represents the right vault, and other represents the left vault.

    Correct answer
    C

    self represents the left vault, and other represents the right vault.

    Explanation

    For the expression potter + weasley, Python passes the left operand as self and the right operand as other to the left operand's __add__ method.

  67. 67

    What should the vault's __add__ method return to make total = potter + weasley work as intended?

    1. A

      The original left-hand vault after replacing its values with the right-hand vault's values.

    2. B

      A tuple containing the two vault objects without combining their contents.

    3. C

      A string containing only the name of the left-hand vault.

    4. D

      A new Vault object containing the summed gallions, sickles, and canuts.

    Correct answer
    D

    A new Vault object containing the summed gallions, sickles, and canuts.

    Explanation

    The example adds each denomination from the two vaults and returns a new Vault initialized with the totals, which can then be assigned to total.

  68. 68

    Why does Python raise an error when adding two Vault objects before __add__ is defined?

    1. A

      Python has no defined addition behavior for that custom class until the programmer implements it.

    2. B

      Python cannot create objects that contain numeric attributes.

    3. C

      Python permits + only between numbers and never between strings or lists.

    4. D

      Python requires every class to define __add__ before it can be instantiated.

    Correct answer
    A

    Python has no defined addition behavior for that custom class until the programmer implements it.

    Explanation

    Python does not automatically know what adding two custom vaults should mean. Defining __add__ supplies that behavior.

  69. 69

    Which statement about using + in Python is supported by the lecture?

    1. A

      It always concatenates values, so it cannot add numbers.

    2. B

      Its meaning is fixed by the variable names rather than by the values' types.

    3. C

      It always means numeric addition, so strings and lists cannot use it.

    4. D

      Its behavior can depend on the operand types; it is used for numeric addition and also for operations such as string concatenation.

    Correct answer
    D

    Its behavior can depend on the operand types; it is used for numeric addition and also for operations such as string concatenation.

    Explanation

    The lecture notes that Python uses + for different operations depending on the data type, including addition and concatenation.

  70. 70

    What does the lecture say about creating arbitrary new operator symbols in Python?

    1. A

      Programmers can define new operators only for strings, not for custom classes.

    2. B

      Programmers can define any new operator by adding a method with any name they choose.

    3. C

      Python permits new operators only when the class inherits from int.

    4. D

      Programmers can overload supported operators, but they cannot define arbitrary new operator characters.

    Correct answer
    D

    Programmers can overload supported operators, but they cannot define arbitrary new operator characters.

    Explanation

    The lecture describes a defined set of special methods for overloading existing operators and notes that Python does not allow arbitrary new operator symbols.

Question 1 of 70
Question 1 of 70

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent