Object-Oriented Programming in Python
- 70Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
Which description best distinguishes procedural programming from object-oriented programming as presented in the lecture?
Which description best distinguishes procedural programming from object-oriented programming as presented in the lecture?
70 questions
- 1
Which description best distinguishes procedural programming from object-oriented programming as presented in the lecture?
- A
Procedural programming organizes work as step-by-step procedures, while object-oriented programming organizes related data and functionality into classes and objects.
- B
Procedural programming requires functions to be anonymous, while object-oriented programming requires every function to have a name.
- C
Procedural programming is available in Python, while object-oriented programming is available only in languages such as Java.
- D
Procedural programming uses only numbers, while object-oriented programming uses only strings and collections.
Correct answer
AProcedural 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.
- A
- 2
What does the ability to pass functions around or use an anonymous function illustrate about Python?
- A
Python has features associated with functional programming, even when a program is not written entirely in that paradigm.
- B
Python functions can be passed around only when they are stored in dictionaries.
- C
Python requires all programs to use functional programming instead of procedures.
- D
Python automatically converts every function into a class method.
Correct answer
APython 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.
- A
- 3
Why can object-oriented programming become especially useful as a program grows?
- A
It guarantees that a program will never contain errors, regardless of its design.
- B
It can help organize increasingly complex programs by grouping related data and behavior together.
- C
It makes every operation run faster by replacing Python's interpreter.
- D
It eliminates the need for functions, variables, or other basic programming constructs.
Correct answer
BIt 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.
- A
- 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?
- A
Move every function into one large function so that the program has fewer definitions.
- B
Replace every function with a global variable so that all code can access the student data.
- C
Make every student-related function anonymous so that its purpose is less tied to its name.
- D
Group student-related data and behavior in a student class to make the program's organization clearer.
Correct answer
DGroup 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.
- A
- 5
What is meant by encapsulating student-related functionality in a student class?
- A
Putting every function in the program inside the student class.
- B
Converting student data into a string before storing it.
- C
Keeping student data and operations related to students together in the class.
- D
Encrypting student data so that no part of the program can read it.
Correct answer
CKeeping 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.
- A
- 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?
- A
It returns an object, and standalone functions cannot return objects.
- B
Its responsibility is student-related, so leaving it outside the class separates related functionality.
- C
It uses input, and classes are not allowed to use input.
- D
It contains two prompts, and a function may prompt the user only once.
Correct answer
BIts 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.
- A
- 7
Which statement best describes the relationship between Python and object-oriented programming?
- A
Python requires every variable to be an instance of a class written by the programmer.
- B
Python is fundamentally limited to object-oriented programming and does not support procedural code.
- C
Python supports object-oriented programming but also allows programmers to solve problems using other paradigms.
- D
Python supports object-oriented programming only when a program imports a special external library.
Correct answer
CPython 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.
- A
- 8
What is a reasonable rule of thumb for using a class in the examples discussed?
- A
A class should be used for every variable, even when no related data or behavior exists.
- B
A class should be used only to represent objects that physically exist in the real world.
- C
A class can be useful for representing a real-world or imagined entity and grouping its related data and behavior.
- D
A class is useful only when its objects must be stored permanently on disk.
Correct answer
CA 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.
- A
- 9
A simple program works correctly without classes. What does the lecture suggest about whether it must be rewritten using object-oriented programming?
- A
It must be rewritten because every correct Python program requires a custom class.
- B
It should be rewritten only if the program uses integers or strings.
- C
It must be rewritten because functions cannot be used in programs that contain classes.
- D
It need not be rewritten; classes are another design tool that can be more useful as problems become more complex.
Correct answer
DIt 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.
- A
- 10
What is the purpose of the
if __name__ == "__main__"guard in the student program?- A
It ensures that the file can be imported only once and that its variables are immutable.
- B
It converts the file into a class whenever another program imports it.
- C
It checks whether the user's name is the word
mainbefore accepting input. - D
It runs the main function when the file is run directly, while avoiding an automatic call when the file is imported.
Correct answer
DIt 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
mainwhen run from the command line, without blindly running it when the file is imported as a module. - A
- 11
What does returning
name, housefrom a Python function actually return?- A
Two independent return values that Python stores separately.
- B
A list that can be changed after the function returns.
- C
A dictionary whose keys are automatically named
nameandhouse. - D
A single tuple containing the name and house.
Correct answer
DA 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.
- A
- 12
How can a caller assign the two elements returned in a tuple to separate variables?
- A
Use sequence unpacking, such as
name, house = get_student(). - B
Use dictionary-key syntax, such as
get_student()["name"]andget_student()["house"]. - C
Call the function twice and assume each call returns a different element.
- D
Use attribute syntax, such as
get_student().nameandget_student().house.
Correct answer
AUse 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.
- A
- 13
Which property distinguishes a tuple from a list in the lecture's comparison?
- A
A tuple is indexed by strings, whereas a list is indexed by numbers.
- B
A tuple is a key-value mapping, whereas a list is a sequence.
- C
A tuple can contain only strings, whereas a list can contain any values.
- D
A tuple is immutable, whereas a list is mutable.
Correct answer
DA 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.
- A
- 14
What is a likely result of attempting
student[1] = "Ravenclaw"whenstudentis a tuple?- A
Python silently converts the tuple into a mutable list.
- B
Python changes the first item because tuple indices start at one.
- C
Python raises a type error because tuple items do not support assignment.
- D
Python changes the second tuple item and leaves the other items unchanged.
Correct answer
CPython 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.
- A
- 15
Why might a programmer choose a tuple rather than a list for a pair of values that should not change?
- A
The tuple allows the values to be accessed by descriptive string keys.
- B
The tuple is required whenever a function returns more than one value.
- C
The tuple communicates that the collection is not intended to be modified, helping prevent accidental changes.
- D
The tuple automatically validates that both values have the same type.
Correct answer
CThe 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.
- A
- 16
How do lists and tuples use square brackets in Python?
- A
Square brackets are used only for lists and cannot be used with tuples.
- B
Square brackets create a tuple, but parentheses must be used to index into it.
- C
Square brackets create both lists and tuples, while parentheses index into both.
- D
Square brackets create a list, and they are also used to index into either a list or a tuple.
Correct answer
DSquare 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.
- A
- 17
How does indexing into a dictionary differ from indexing into a list or tuple?
- A
A dictionary is accessed using attributes, while lists and tuples are accessed using function calls.
- B
A dictionary is accessed using keys, while lists and tuples are accessed using numeric indices.
- C
A dictionary is accessed using numeric indices, while lists and tuples are accessed using string keys.
- D
A dictionary is accessed only by its values, while lists and tuples are accessed by their keys.
Correct answer
BA dictionary is accessed using keys, while lists and tuples are accessed using numeric indices.
Explanation
Lists and tuples use numeric positions such as
0and1; dictionaries use keys, such as the stringsnameandhouse. - A
- 18
Why can a dictionary be clearer than a tuple for storing a student's name and house?
- A
A dictionary automatically checks that the house is one of Hogwarts' four houses.
- B
A dictionary stores values in alphabetical order, making numeric positions unnecessary.
- C
Keys such as
nameandhousedescribe the values, so a reader need not remember their numeric positions. - D
A dictionary guarantees that its values cannot be changed after creation.
Correct answer
CKeys such as
nameandhousedescribe 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.
- A
- 19
Which statement correctly describes mutability among the three collections discussed?
- A
Tuples and dictionaries are immutable, while lists are mutable.
- B
Lists and tuples are mutable, while dictionaries are immutable.
- C
Lists and dictionaries are mutable, while tuples are immutable.
- D
Lists, tuples, and dictionaries are all immutable.
Correct answer
CLists and dictionaries are mutable, while tuples are immutable.
Explanation
The lecture describes lists and dictionaries as mutable collections and tuples as immutable.
- A
- 20
What is the purpose of
type(value)in the exploration shown in the lecture?- A
It can reveal the type or class of a value, such as
int,str,list, ordict. - B
It converts any value into a string without changing its underlying type.
- C
It creates a new class named after the value's contents.
- D
It checks whether a value is valid for a particular class's initializer.
Correct answer
AIt can reveal the type or class of a value, such as
int,str,list, ordict.Explanation
The
typefunction can be used to inspect the type of a value. The examples show integers, strings, lists, and dictionaries as instances of their respective classes. - A
- 21
What is a class in the lecture's blueprint analogy?
- A
A collection that must contain only strings and numeric indices.
- B
A function that can be called only from the command line.
- C
A named blueprint or mold used to define a type of data and the structure or behavior of its objects.
- D
A specific value stored in a variable after the program finishes running.
Correct answer
CA 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.
- A
- 22
What is an object in relation to a class?
- A
A collection of class names stored in a dictionary.
- B
The source-code file in which the class was first written.
- C
A special method that runs before the class is defined.
- D
A particular instance created from the class's definition or blueprint.
Correct answer
DA 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.
- A
- 23
In the student example, what does
student = Student()do?- A
It converts the class definition into a string and stores that string.
- B
It defines a new class named
studentwith a lowercase initial letter. - C
It calls the
Studentobject's__str__method to create a formatted name. - D
It calls the
Studentclass to create a student object and assigns that object to the variablestudent.
Correct answer
DIt calls the
Studentclass to create a student object and assigns that object to the variablestudent.Explanation
Calling the class name with parentheses creates an instance of that class. The resulting object is assigned to the variable on the left.
- A
- 24
How are attributes such as
nameandhouseaccessed on the student object in the example?- A
With dot notation, such as
student.nameandstudent.house. - B
With numeric indexing, such as
student[0]andstudent[1]. - C
With dictionary-key syntax, such as
student["name"]andstudent["house"]. - D
With function-call syntax, such as
student(name)andstudent(house).
Correct answer
AWith dot notation, such as
student.nameandstudent.house.Explanation
The example stores and accesses class attributes using dot notation, as in
student.nameandstudent.house. - A
- 25
What is the role of the
selfparameter in an instance method?- A
It provides access to the current object so the method can read or set that object's attributes.
- B
It stores the arguments passed by every other object of the same class.
- C
It prevents the method from accessing any data outside the function.
- D
It refers to the class's source file so the method can import its code.
Correct answer
AIt 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. - A
- 26
Why does
__init__includeselfeven though a call such asStudent(name, house)passes onlynameandhouseexplicitly?- A
The caller must secretly provide
selfas the first argument, but Python ignores it. - B
The
Studentclass automatically convertsnameintoselfandhouseinto an argument. - C
Python automatically supplies the new object's reference as
self, in addition to the explicitly provided arguments. - D
selfis a default value that replacesnameif the user leaves it blank.
Correct answer
CPython 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,
selfis present in the method signature but is not supplied explicitly in the class call. - A
- 27
What is the primary purpose of the
__init__method described in the lecture?- A
To select a random object from a list of possible instances.
- B
To initialize an object's contents after the object has been created.
- C
To convert an object to a user-friendly string whenever it is printed.
- D
To define the class's name and make it available to imported modules.
Correct answer
BTo 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. - A
- 28
What does the lecture mean by calling
Student(name, house)a constructor call?- A
It calls a function that prints the student's name and house but creates no object.
- B
It unpacks a tuple into two separate student objects.
- C
It invokes the class to create and initialize a student object using the supplied arguments.
- D
It modifies the class definition so that every student has the same name and house.
Correct answer
CIt 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.
- A
- 29
What is the technical distinction between
__new__and__init__noted in the lecture?- A
They are two names for the same method, and Python calls them interchangeably.
- B
__init__creates the class, while__new__prints the object as a string. - C
__new__validates user input, while__init__catches all exceptions automatically. - 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__. - A
- 30
Why is
self.name = nameused inside__init__?- A
It changes the local variable
nameinto a global variable shared by every object. - B
It stores the incoming
nameargument as an attribute of the current object. - C
It asks Python to look up a dictionary key named
nameon the current object. - D
It renames the class so that its name matches the user's input.
Correct answer
BIt stores the incoming
nameargument as an attribute of the current object.Explanation
The assignment creates or sets an instance attribute called
nameon the object referenced byself, using the method'snameargument as its value. - A
- 31
Which statement about the attributes created in the student example is supported by the lecture?
- A
They are dictionary keys that can be accessed only with square brackets.
- B
They must be integers because Python classes cannot store strings.
- C
They are class variables automatically shared by every student object, and they must be strings.
- D
They are instance variables belonging to a particular student object, and their values can be various data types.
Correct answer
DThey 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.
- A
- 32
What is a method in the lecture's terminology?
- A
A variable stored only outside every class.
- B
A function defined inside a class.
- C
A special kind of tuple that can hold named keys.
- D
A particular instance created from a class.
Correct answer
BA 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.
- A
- 33
What does a class's
__str__method control?- A
The number of arguments accepted by every method in the class.
- B
The validation rules applied when the object is first created.
- C
The object's memory address and the location at which Python stores its class definition.
- D
The string representation returned when an object is converted to a string, such as when it is printed.
Correct answer
DThe 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. - A
- 34
Why does an instance's
__str__method receiveselfwhenprint(student)causes it to be called?- A
The
printfunction passes the object's name as a string and Python converts it intoself. - B
The method uses
selfto locate the class's source file before printing it. - C
Python automatically passes a reference to the object being converted, allowing the method to use its attributes.
- D
The programmer must pass
selftoprintexplicitly after the student object.
Correct answer
CPython 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. - A
- 35
How does the lecture distinguish
__str__from__repr__?- A
__str__is a class method, while__repr__is a property setter. - B
__str__is used only for numbers, while__repr__is used only for dictionaries. - C
__str__is generally intended to be user-friendly, while__repr__is generally intended for developers and may include more information. - 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. - A
- 36
Why might a class validate a student's name and house in its
__init__method?- A
It ensures Python will never allow any later changes to the object's attributes.
- B
It can reject invalid data when a student object is being initialized, keeping student-related rules with the class.
- C
It prevents the user from importing the student class into another program.
- D
It automatically turns both values into immutable tuples.
Correct answer
BIt 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.
- A
- 37
What is the role of
raise ValueError("missing name")in the validation example?- A
It prints a warning and then guarantees that the program continues normally.
- B
It exits the entire program immediately without allowing exception handling.
- C
It signals an invalid value by raising an exception with an explanatory message.
- D
It returns
Nonebefore the student object has been created.
Correct answer
CIt signals an invalid value by raising an exception with an explanatory message.
Explanation
The
raisekeyword lets a programmer signal an exception. A message such asmissing namehelps explain what went wrong; code may catch the exception withtryandexcept. - A
- 38
Why does the lecture prefer raising an exception over calling
sys.exitwhen invalid data is encountered?- A
Raising an exception automatically fixes the invalid input and continues with a valid object.
- B
Raising an exception signals the problem without necessarily forcing the entire program to terminate immediately.
- C
sys.exitcan be used only inside a class, while exceptions can be used only outside classes. - D
sys.exitconverts invalid values into strings, while exceptions convert them into integers.
Correct answer
BRaising 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.
- A
- 39
If a student's house must be one of four recognized values, which validation condition matches the lecture's approach?
- A
Replace every unrecognized house with the first item in the list without notifying the caller.
- B
Store any supplied house and rely on the
__str__method to correct it later. - C
Raise a
ValueErrorif the supplied house is not in the list of valid houses. - D
Reject the input only if it is a string rather than an integer.
Correct answer
CRaise a
ValueErrorif 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
ValueErrorotherwise. - A
- 40
Why might a class provide a getter and setter for a property?
- A
They allow code to control how an attribute is retrieved or changed, including validating assigned values.
- B
They convert every attribute into a class variable shared by all objects.
- C
They make the attribute impossible to read or change from any part of the program.
- D
They allow Python to infer the attribute's value without storing it.
Correct answer
AThey 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.
- A
- 41
What does the
@propertydecorator do in the house example?- A
It makes the house value a class variable.
- B
It defines a setter so any assignment to the property bypasses validation.
- C
It defines a getter so the method can be accessed using property-style syntax such as
student.house. - D
It converts the house attribute into a dictionary key.
Correct answer
CIt defines a getter so the method can be accessed using property-style syntax such as
student.house.Explanation
The
@propertydecorator marks a method as the getter for a property, allowing it to be read using attribute-style syntax. - A
- 42
How is a setter associated with a property named
house?- A
Define a class method named
housethat takes the class and no other arguments. - B
Define a method decorated with
@house.setter, usingselfand the new house value as parameters. - C
Define a method decorated with
@property.setter, using only the new house value as a parameter. - D
Define a function named
set_houseoutside the class and call it automatically fromprint.
Correct answer
BDefine a method decorated with
@house.setter, usingselfand the new house value as parameters.Explanation
The lecture uses
@house.setterfor the setter of thehouseproperty. The setter receivesselfand the value being assigned. - A
- 43
Why does the example store the house value in
self._houserather thanself.houseinside the getter and setter?- A
The underscore-prefixed instance variable avoids colliding with the property named
house. - B
Python requires all properties to store values in variables that start with underscores.
- C
The underscore converts the house into an immutable class variable.
- D
Using
self.housewould make the getter return the student's name instead.
Correct answer
AThe 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. - A
- 44
Why does assigning
self.house = housein__init__help centralize validation?- A
Because
self.housealways refers directly to_houseand cannot call a method. - B
Because assignment through the property invokes its setter, so initialization can use the same validation as later changes.
- C
Because the assignment changes the property into a tuple before validation occurs.
- D
Because Python skips the setter during initialization but invokes it when printing the object.
Correct answer
BBecause assignment through the property invokes its setter, so initialization can use the same validation as later changes.
Explanation
The example deliberately assigns through
self.housein__init__, causing the setter to run. This avoids duplicating the same house-validation logic in multiple places. - A
- 45
What does a single leading underscore in a Python instance-variable name conventionally communicate?
- A
The variable is fully private and Python will reject any access from outside its class.
- B
The variable is intended for internal use and other programmers should avoid changing it, though Python does not strictly prevent access.
- C
The variable is shared among every instance of the class.
- D
The variable can be read but can never be assigned.
Correct answer
BThe 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.
- A
- 46
What is a key limitation of property-based validation in Python, according to the lecture?
- A
A property setter can validate values only during printing, not during assignment.
- B
A programmer can still deliberately access the underscore-prefixed instance variable directly, bypassing the property.
- C
A property cannot be used with strings such as student names or houses.
- D
A property makes every assigned value immutable after the first assignment.
Correct answer
BA 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. - A
- 47
What does a method decorated with
@classmethodreceive by convention?- A
The return value of the class's
__str__method. - B
A dictionary containing every instance variable of every object.
- C
A reference to the current object, always named
self, rather than the class. - D
A reference to the class, commonly named
cls, rather than a reference to a particular instance.
Correct answer
DA 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 asself. - A
- 48
When is a class method appropriate in the Sorting Hat example?
- A
When the method needs to convert each hat object into a user-facing string.
- B
When the sorting behavior belongs to the Sorting Hat class and does not depend on a particular hat object.
- C
When a method needs to initialize every object created from the class.
- D
When the behavior must read a different private attribute from each hat instance.
Correct answer
BWhen 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.
- A
- 49
What is a class variable?
- A
A value that can be accessed only after a class is imported from a package.
- B
A variable defined on the class itself and shared as a class-level value rather than stored separately on each instance.
- C
A local variable created only while an instance method is running.
- D
A variable automatically passed as
selfto every method.
Correct answer
BA 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.
- A
- 50
Why can the Sorting Hat's list of houses be a class variable rather than an instance variable?
- A
Each individual house needs a separate Sorting Hat object to store its name.
- B
The list is shared information for the Sorting Hat class and does not need a separate copy for each hat object.
- C
The list must be a class variable because Python cannot store lists on objects.
- D
A class variable makes the list immutable, which is required for random selection.
Correct answer
BThe 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.
- A
- 51
How does the
sortmethod select a house in the Sorting Hat example?- A
It uses
typeto determine the student's class and then selects a fixed house. - B
It calls
inputto ask the student to choose a house and stores the response in a tuple. - C
It uses
random.choiceon the list of houses, after importing therandommodule. - D
It uses the
__add__method to combine the four house names.
Correct answer
CIt uses
random.choiceon the list of houses, after importing therandommodule.Explanation
The example imports
randomand usesrandom.choiceon the available houses to select one randomly. - A
- 52
Why can
Hat.sort("Harry")work aftersortis made a class method?- A
The method can be called through the class without first creating a Hat instance.
- B
The method is actually a static method and receives no arguments of any kind.
- C
The class name is converted into an instance when the argument is a string.
- D
The class call automatically creates four Hat objects, one for each house.
Correct answer
AThe 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. - A
- 53
What does the
clsparameter allow a class method to do in the Sorting Hat example?- A
Refer to a specific hat object and access its instance variable, such as
self.houses. - B
Refer to the class and access its class variable, such as
cls.houses. - C
Refer to the current user's input without receiving it as an argument.
- D
Create an exception without using the
raisekeyword.
Correct answer
BRefer 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 ascls.houses. - A
- 54
Why was
Student.get()designed as a class method in the revised student program?- A
It allows the method to print a student without receiving any information.
- B
It can gather input and create a student without requiring an existing student object first.
- C
It ensures that every student shares the same name and house.
- D
It prevents the student class from having an initializer.
Correct answer
BIt 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. - A
- 55
What does
return cls(name, house)do inside a class method ofStudent?- A
It changes the class's name and house variables for every instance.
- B
It creates and returns an instance of the class represented by
cls, initialized with the supplied values. - C
It returns the class definition itself without creating an object.
- D
It calls the class's
__str__method and returns the formatted string.
Correct answer
BIt creates and returns an instance of the class represented by
cls, initialized with the supplied values.Explanation
clsrefers to the class, so callingcls(name, house)creates an instance of that class using the given arguments and returns it. - A
- 56
Which statement correctly distinguishes instance methods from class methods?
- A
Instance methods must use a decorator; class methods never use decorators.
- B
Instance methods operate with access to a particular object through
self; class methods receive the class throughcls. - C
Instance methods receive the class through
cls; class methods receive a particular object throughself. - D
Instance methods cannot access attributes; class methods can access only local variables.
Correct answer
BInstance methods operate with access to a particular object through
self; class methods receive the class throughcls.Explanation
The lecture distinguishes methods by what their first argument represents:
selfis a particular object, whileclsis the class. Instance methods are the default when no class-method decorator is used. - A
- 57
What is inheritance in object-oriented programming?
- A
A relationship in which a class can inherit attributes and methods from another class.
- B
A method for making a tuple mutable after it has been created.
- C
A rule that every class must inherit from two parent classes.
- D
A process that converts an object into a string when it is printed.
Correct answer
AA 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.
- A
- 58
In the Wizard example, if
Studentinherits fromWizard, which class is the superclass?- A
Wizardis the superclass, andStudentis its subclass. - B
Studentis the superclass, andWizardis its subclass. - C
Neither is a superclass because they each have an
__init__method. - D
Both are superclasses because they are defined in the same file.
Correct answer
AWizardis the superclass, andStudentis its subclass.Explanation
The class named in the inheritance declaration,
Wizard, is the parent or superclass;Studentis the subclass that inherits from it. - A
- 59
Why introduce a shared
Wizardclass for both students and professors in the example?- A
Python requires all classes with different initializers to inherit from a third class.
- B
They share functionality such as having a name, so that common behavior and validation can be written once.
- C
It allows professors and students to become the same type of object.
- D
They must share a house and subject, so those values can be stored as one class variable.
Correct answer
BThey 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.
- A
- 60
What does
super().__init__(name)accomplish in a subclass initializer?- A
It calls the subclass initializer a second time with no arguments.
- B
It calls the superclass's initializer so the inherited part of the object can be initialized.
- C
It converts the name into a class variable shared by all subclasses.
- D
It creates a new superclass object separate from the subclass object.
Correct answer
BIt 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. - A
- 61
In the Wizard hierarchy, what can a
Studentclass do after inheriting fromWizardand callingsuper().__init__(name)?- A
Make the student's name immutable by converting it into a tuple.
- B
Avoid creating any student object because the superclass already exists.
- C
Reuse the professor's subject field without defining a professor class.
- D
Reuse the superclass's name handling while adding student-specific data such as a house.
Correct answer
DReuse 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.
- A
- 62
What happens to inherited functionality through a deeper inheritance hierarchy?
- A
A subclass can inherit functionality from its parent and more distant ancestor classes as well.
- B
A subclass inherits only class variables, not methods or instance behavior.
- C
A subclass inherits only from the class immediately above it and never from more distant ancestors.
- D
A subclass loses all inherited functionality when it defines its own initializer.
Correct answer
AA 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.
- A
- 63
Which statement about multiple inheritance is supported by the lecture?
- A
Python forbids a class from inheriting from more than one parent.
- B
A class can inherit from multiple parents only if they are defined in separate files.
- C
Multiple inheritance is required whenever a class has two attributes.
- D
Python has ways to inherit from multiple parents, though the demonstration uses a single inheritance path.
Correct answer
DPython 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.
- A
- 64
What is operator overloading?
- A
Using an operator without defining any behavior for the objects involved.
- B
Creating entirely new keyboard symbols that Python will recognize as operators.
- C
Defining how a familiar operator, such as
+, behaves for objects of a custom class. - D
Replacing every built-in operator with a function that accepts only strings.
Correct answer
CDefining 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.
- A
- 65
What does the
__add__method represent for a custom class?- A
The behavior invoked for every comparison operator, regardless of its symbol.
- B
The behavior invoked whenever an object is printed, with no operands passed in.
- C
The process of creating the class, with the class name passed as the only argument.
- D
The behavior invoked for the
+operator, with the left and right operands passed to the method.
Correct answer
DThe 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. - A
- 66
In the vault example, what do
selfandotherrepresent inside__add__when evaluatingpotter + weasley?- A
selfrepresents the sum, andotherrepresents the number of coins. - B
Both represent the class
Vault, not either operand. - C
selfrepresents the left vault, andotherrepresents the right vault. - D
selfrepresents the right vault, andotherrepresents the left vault.
Correct answer
Cselfrepresents the left vault, andotherrepresents the right vault.Explanation
For the expression
potter + weasley, Python passes the left operand asselfand the right operand asotherto the left operand's__add__method. - A
- 67
What should the vault's
__add__method return to maketotal = potter + weasleywork as intended?- A
The original left-hand vault after replacing its values with the right-hand vault's values.
- B
A tuple containing the two vault objects without combining their contents.
- C
A string containing only the name of the left-hand vault.
- D
A new
Vaultobject containing the summed gallions, sickles, and canuts.
Correct answer
DA new
Vaultobject containing the summed gallions, sickles, and canuts.Explanation
The example adds each denomination from the two vaults and returns a new
Vaultinitialized with the totals, which can then be assigned tototal. - A
- 68
Why does Python raise an error when adding two
Vaultobjects before__add__is defined?- A
Python has no defined addition behavior for that custom class until the programmer implements it.
- B
Python cannot create objects that contain numeric attributes.
- C
Python permits
+only between numbers and never between strings or lists. - D
Python requires every class to define
__add__before it can be instantiated.
Correct answer
APython 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. - A
- 69
Which statement about using
+in Python is supported by the lecture?- A
It always concatenates values, so it cannot add numbers.
- B
Its meaning is fixed by the variable names rather than by the values' types.
- C
It always means numeric addition, so strings and lists cannot use it.
- 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
DIts 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. - A
- 70
What does the lecture say about creating arbitrary new operator symbols in Python?
- A
Programmers can define new operators only for strings, not for custom classes.
- B
Programmers can define any new operator by adding a method with any name they choose.
- C
Python permits new operators only when the class inherits from
int. - D
Programmers can overload supported operators, but they cannot define arbitrary new operator characters.
Correct answer
DProgrammers 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.
- A

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