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

  • 75Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Paradigms And Data

What is a programming paradigm, and which three paradigms are discussed in the content?

75 questions

  1. 1

    What is a programming paradigm, and which three paradigms are discussed in the content?

    Model answer

    A programming paradigm is an approach to solving problems with code. The content discusses procedural, functional, and object-oriented programming.

    Explanation

    Languages and programs can organize problem-solving in different ways; Python supports features associated with all three paradigms.

  2. 2

    How does procedural programming typically organize a program?

    Model answer

    It organizes code as procedures or functions that carry out steps, often in a top-to-bottom sequence.

    Explanation

    The content describes procedural code as proceeding step by step, much like an algorithm.

  3. 3

    What feature of functional programming had already appeared in the course before the object-oriented programming material?

    Model answer

    Functions had been passed around, and an anonymous function had been used.

    Explanation

    Passing functions and using anonymous functions are examples of functional-programming features.

  4. 4

    Why can object-oriented programming be useful as programs become larger and more complicated?

    Model answer

    It provides a way to organize related data and functionality together, which can make complex programs easier to design and maintain.

    Explanation

    The content presents OOP as a solution to organizational problems that become more apparent as programs grow.

  5. 5

    What is a tuple, and how can a function return multiple pieces of information using one?

    Model answer

    A tuple is an immutable collection of values. Returning values separated by commas returns one tuple containing those values.

    Explanation

    The apparent return of multiple values is technically the return of a single tuple.

  6. 6

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

    Model answer

    It can unpack the tuple by placing corresponding variable names, separated by commas, on the left side of an assignment.

    Explanation

    For example, two returned values can be assigned to separate name and house variables through unpacking.

  7. 7

    How do tuples and lists differ in mutability, and when might a tuple be preferable?

    Model answer

    A tuple cannot have its contents reassigned after creation, while a list can be changed. A tuple can be preferable when its values should remain fixed, helping prevent accidental changes.

    Explanation

    The content presents immutability as a defensive programming choice that can reduce mistakes.

  8. 8

    What error occurs when code tries to assign a new value to an item in a tuple, and what does it indicate?

    Model answer

    Python raises a TypeError stating that a tuple does not support item assignment; this indicates that tuple items cannot be changed.

    Explanation

    The attempted reassignment demonstrates the tuple's immutability.

  9. 9

    How do lists and tuples represent nested collections?

    Model answer

    Either can contain other collections, including lists or tuples, as elements.

    Explanation

    The content notes that there is no restriction preventing nested lists or nested tuples.

  10. 10

    How do you create a list or tuple, and how do you access an element in either?

    Model answer

    Lists are created with square brackets and tuples can be created with parentheses or a comma. Both are indexed with square brackets.

    Explanation

    Square brackets indicate a list when creating one, but are also used to index into both lists and tuples.

  11. 11

    What is a dictionary, and what is its main advantage over representing related values by numeric positions?

    Model answer

    A dictionary is a mutable collection of key-value pairs. Descriptive keys make it clearer which value represents each field than relying on numeric positions.

    Explanation

    Keys such as name and house give values explicit meaning, reducing confusion about positions such as zero and one.

  12. 12

    How do you access a dictionary value, and how does this differ from accessing a list or tuple value?

    Model answer

    A dictionary value is accessed with its key, commonly a string, while a list or tuple is accessed with a numeric index.

    Explanation

    The student example uses keys such as name and house; lists and tuples use positions such as zero and one.

  13. 13

    What does a class provide, and how does it help programmers define their own data types?

    Model answer

    A class is a named blueprint or mold for data. Defining a class lets programmers create custom data types suited to their programs.

    Explanation

    The content contrasts custom classes with using general-purpose tuples, lists, or dictionaries to represent an entity.

  14. 14

    Distinguish between a class and an object, using the blueprint metaphor.

    Model answer

    A class is the blueprint or mold; an object is a specific instance created from it.

    Explanation

    A class defines the structure, while an object is an individual realization of that structure.

  15. 15

    What does it mean to instantiate a class?

    Model answer

    To instantiate a class is to create an object, or instance, of that class.

    Explanation

    A constructor call such as Student(...) creates a particular Student object from the class.

  16. 16

    How are attributes assigned to and accessed on an object?

    Model answer

    Dot notation is used to assign and access an object's attributes, such as student.name.

    Explanation

    Dot notation provides access to values stored inside an object.

  17. 17

    What are instance variables, and how are they related to object attributes?

    Model answer

    Instance variables are variables stored in a particular object; they are the object's attributes.

    Explanation

    For example, a Student object can store name and house as instance variables.

  18. 18

    What is the purpose of the __init__ method in a Python class?

    Model answer

    It initializes an object after it has been created, commonly by assigning values to its instance variables.

    Explanation

    The method can set fields such as a student's name and house when a Student object is initialized.

  19. 19

    Why does an instance method such as __init__ take self as its first parameter?

    Model answer

    self refers to the current object, allowing the method to access and populate that object's attributes.

    Explanation

    Python automatically passes a reference to the object being initialized as the first argument.

  20. 20

    When a constructor call passes name and house to a class, how do those values reach the object's instance variables?

    Model answer

    Python calls __init__, passing the new object as self along with the supplied values; the method assigns them, for example, to self.name and self.house.

    Explanation

    The constructor call supplies the data, and __init__ stores it in the newly created object.

  21. 21

    How does Python distinguish object creation from object initialization?

    Model answer

    __new__ handles creating an object, while __init__ initializes its contents. Programmers generally define __init__ and let Python handle __new__.

    Explanation

    The content identifies __new__ as the method involved in creating an empty object and __init__ as the method for initializing it.

  22. 22

    Why might a class be preferable to a dictionary for representing a student?

    Model answer

    A class provides a named, purpose-built type and can group a student's data with related behavior and validation.

    Explanation

    Unlike a general-purpose dictionary, a class can define standardized fields, methods, and rules for acceptable data.

  23. 23

    Why might a student class store several names in a list rather than create a separate instance variable for every name?

    Model answer

    A list can hold a variable number of names in one instance variable, avoiding a proliferation of separate variables.

    Explanation

    The content suggests a list such as self.names for multiple values, while noting that the data model should fit the entity.

  24. 24

    How are classes and objects represented in memory, according to the content?

    Model answer

    A class is code defining the type; an object occupies some amount of computer memory, with Python managing where it is stored.

    Explanation

    The programmer works with objects at a higher level while the interpreter handles memory details.

  25. 25

    Why is printing an object without a custom string method often unhelpful?

    Model answer

    Python's default display may show a technical representation that includes the object's type and a memory-related address rather than meaningful data.

    Explanation

    The default output is intended as a representation of the object, not necessarily as a useful description for a program's user.

  26. 26

    What does the special method __str__ do, and when is it called?

    Model answer

    __str__ defines an object's user-friendly string representation. Python calls it when an operation such as print needs the object as a string.

    Explanation

    The method can format an object's attributes into readable output, such as a student's name and house.

  27. 27

    How does __repr__ differ in intended audience from __str__?

    Model answer

    __repr__ is generally intended as a representation for developers, while __str__ is generally intended as readable output for users.

    Explanation

    Both methods can be customized, but their typical audiences differ.

  28. 28

    What is a method, and how does it differ from a function outside a class?

    Model answer

    A method is a function defined inside a class; it can provide behavior associated with that class or its objects.

    Explanation

    The content describes methods as functions inside classes, including special methods and programmer-defined methods.

  29. 29

    How can a class method use an object's data to produce behavior specific to that object?

    Model answer

    An instance method uses self to access the current object's instance variables and can base its result on them.

    Explanation

    For example, a student's charm method can inspect self.patronus to choose an appropriate result.

  30. 30

    What is the role of a getter and a setter for a property?

    Model answer

    A getter retrieves an attribute's value, while a setter assigns a value and can validate it before storing it.

    Explanation

    Using a setter lets a class control what values can be assigned to a property.

  31. 31

    How are a property getter and its setter declared in Python?

    Model answer

    A getter is decorated with @property; the setter is declared with @property_name.setter above a method with the same name.

    Explanation

    For example, a house property uses @property for its getter and @house.setter for its setter.

  32. 32

    How many parameters do property getters and setters normally have, and why?

    Model answer

    A getter has self; a setter has self and the value being assigned. The setter needs that extra value to know what to store.

    Explanation

    Python supplies self automatically for both methods, while the assignment supplies the value to the setter.

  33. 33

    How can a property setter prevent a student's house from being set to an invalid value?

    Model answer

    The setter checks whether the proposed house is in the allowed set and raises a ValueError if it is not.

    Explanation

    Putting this validation in the setter checks values assigned both during initialization and through later property assignments.

  34. 34

    Why might a property use an instance variable such as _house instead of an instance variable named house?

    Model answer

    The property and its getter/setter use the name house; storing the underlying value as _house avoids a name collision and unintended recursive access.

    Explanation

    The property is the public-facing attribute, while the underscore-prefixed variable stores the value internally.

  35. 35

    Why should initialization assign through a property rather than directly to its underscore-prefixed backing variable?

    Model answer

    Assigning through the property invokes the setter, so its validation is applied during initialization too.

    Explanation

    Using self.house = house in __init__ runs the property setter; assigning directly to self._house would bypass it.

  36. 36

    What does a leading underscore on a Python instance variable communicate, and does it prevent access?

    Model answer

    It conventionally signals that the variable is intended for internal use and should not be touched directly, but it does not prevent access.

    Explanation

    Python relies on convention here rather than enforcing private visibility; code can still access an underscore-prefixed variable.

  37. 37

    How does Python's approach to public and private attributes differ from a language that enforces visibility restrictions?

    Model answer

    Python commonly relies on conventions such as leading underscores rather than enforcing that other code cannot access an attribute.

    Explanation

    The content contrasts Python's convention-based approach with languages that prevent certain accesses directly.

  38. 38

    Why is printing an error message alone insufficient when invalid data must prevent object creation?

    Model answer

    Printing does not stop execution, so the program might continue and create an object with invalid data.

    Explanation

    The content explains that validation must signal failure in a way that prevents normal processing from continuing unchecked.

  39. 39

    Why can returning None from __init__ not serve as a way to cancel object creation?

    Model answer

    The object has already been created before its initialization method runs, so returning None does not undo its existence.

    Explanation

    Object creation and initialization are distinct steps; an error must be signaled if initialization cannot proceed validly.

  40. 40

    What does the raise keyword allow a programmer to do?

    Model answer

    It allows a programmer to raise an exception to signal that an error or exceptional condition has occurred.

    Explanation

    Programmers can raise exceptions, including a ValueError with an explanatory message, and callers can handle them with try and except.

  41. 41

    Why can class-based validation provide better control over data than simply putting values into a dictionary?

    Model answer

    A class can validate values as they are initialized or set, while a dictionary accepts key-value assignments without enforcing those rules automatically.

    Explanation

    The content uses a class to reject blank names and houses outside the allowed Hogwarts set.

  42. 42

    What is a class method, and how does its first parameter differ from that of an instance method?

    Model answer

    A class method is associated with the class rather than a particular object. Its first parameter conventionally refers to the class, often named cls, instead of an instance named self.

    Explanation

    The @classmethod decorator marks the method, and Python supplies a reference to the class.

  43. 43

    What is a class variable, and how does it differ from an instance variable?

    Model answer

    A class variable belongs to the class and is shared by its objects; an instance variable belongs to a particular object.

    Explanation

    A list of houses shared by a Sorting Hat class is a class variable, whereas a student's name is specific to a Student object.

  44. 44

    Why might a class method be suitable for a Sorting Hat that should not be instantiated multiple times?

    Model answer

    A class method lets the program use the class's functionality directly without creating a particular Hat object.

    Explanation

    The example treats the Sorting Hat as a singleton-like entity and uses the class as a container for related data and behavior.

  45. 45

    How can a class method create and return an instance of its own class?

    Model answer

    It can call the class reference supplied to it, such as cls(name, house), which constructs and returns an instance.

    Explanation

    Using cls lets the method construct an object of the current class without hard-coding the class name.

  46. 46

    Why might a class method named get be preferable to a separate get_student function?

    Model answer

    It keeps student-related functionality inside the Student class and lets the method create a student without first requiring a Student object.

    Explanation

    The class method avoids a circular dependency in which an object would have to exist before calling the function that obtains and creates it.

  47. 47

    What is a static method, and how is it marked in Python?

    Model answer

    A static method is another kind of method in a class and is marked with the @staticmethod decorator.

    Explanation

    The content identifies static methods as an additional method category but does not develop their behavior further.

  48. 48

    What is encapsulation in the context of object-oriented program design?

    Model answer

    Encapsulation is organizing related data and functionality together, commonly inside a class.

    Explanation

    Keeping student-related fields and behaviors in the Student class makes that functionality easier to locate and organize.

  49. 49

    Why might a standalone function located far from a class be considered a design smell if it handles that class's data?

    Model answer

    It separates related functionality from the data and class it concerns, making the program harder to organize as it grows.

    Explanation

    The content describes this separation as a possible code smell, even if the program still works correctly.

  50. 50

    When could a short implementation create and return a dictionary in one expression, and when might a more expanded version be clearer?

    Model answer

    A compact expression is reasonable for a short, simple dictionary; for longer or more complex construction, separate lines or intermediate variables may improve readability.

    Explanation

    The content treats readability as the guide: temporary variables are useful when they make the code easier to understand.

  51. 51

    What is inheritance, and what does it let one class reuse from another?

    Model answer

    Inheritance lets a class derive from another class and reuse its attributes and methods.

    Explanation

    A subclass can borrow common functionality from a superclass and add its own specialized behavior.

  52. 52

    In the Wizard, Student, and Professor example, which class is the superclass and which are the subclasses?

    Model answer

    Wizard is the superclass; Student and Professor are subclasses that inherit from Wizard.

    Explanation

    The example factors their common name-related behavior into Wizard and leaves student- or professor-specific fields in the subclasses.

  53. 53

    Why was a Wizard superclass introduced for Student and Professor?

    Model answer

    Both classes share a name field and related validation, so putting that common behavior in Wizard avoids duplicated code.

    Explanation

    The content identifies repeated initialization and name-checking code as a reason to use inheritance.

  54. 54

    How does a subclass call its superclass's initialization method in Python?

    Model answer

    It calls super().__init__(...), passing the arguments needed by the superclass.

    Explanation

    In the example, Student and Professor call the Wizard initializer to reuse name validation and assignment.

  55. 55

    What is the relationship between a subclass and a superclass?

    Model answer

    A subclass derives from and inherits from its superclass; the superclass is also called the parent class, and the subclass the child class.

    Explanation

    The content also uses the terms descendant and ancestor for classes in an inheritance hierarchy.

  56. 56

    What functionality can a class inherit from a grandparent or a more distant ancestor?

    Model answer

    It can inherit functionality from higher levels of its class hierarchy, not just from its immediate parent.

    Explanation

    Inherited behavior can pass down through multiple levels of the hierarchy.

  57. 57

    Can a subclass override inherited functionality, and why might it do so?

    Model answer

    Yes. It can override inherited functionality to make that subclass behave differently.

    Explanation

    The content notes that subclasses can customize behavior while still inheriting common functionality.

  58. 58

    Can a class inherit from more than one parent in Python?

    Model answer

    Yes, Python provides ways to use multiple inheritance, although the example uses a single inheritance path.

    Explanation

    The content confirms that multiple-parent inheritance is possible but does not explore its details.

  59. 59

    How does inheritance organize the built-in Python exception types?

    Model answer

    Exception types form a hierarchy: specific types such as ValueError inherit from broader types such as Exception, which inherits from BaseException.

    Explanation

    The hierarchy lets specialized exceptions share common behavior.

  60. 60

    Why might a program catch a broad superclass exception rather than list several specific exception types?

    Model answer

    It can handle multiple related exception types together when they should be handled in the same way or when the exact type is uncertain.

    Explanation

    A try/except clause can catch a common parent type to cover its descendant exceptions.

  61. 61

    What is operator overloading?

    Model answer

    Operator overloading lets a class define how an existing operator, such as +, behaves for its objects.

    Explanation

    The operator's meaning can depend on the type of the operands.

  62. 62

    How has Python already used the plus operator for meanings other than numeric addition?

    Model answer

    It can concatenate strings and combine lists, in addition to adding numbers.

    Explanation

    The content uses these built-in behaviors to illustrate that an operator can have type-dependent meanings.

  63. 63

    Which special method supports adding two objects with the + operator, and what does it return in the Vault example?

    Model answer

    __add__ supports +. The Vault implementation returns a new Vault containing the summed coin amounts.

    Explanation

    The method creates a result object rather than merely printing or changing one of the original vaults.

  64. 64

    When Python evaluates left + right for objects with a suitable __add__ method, what information is passed to that method?

    Model answer

    The left operand is passed as self and the right operand as the other argument.

    Explanation

    This gives the method access to both operands so it can define their combined result.

  65. 65

    How does the Vault example combine two vaults using operator overloading?

    Model answer

    Its __add__ method adds the corresponding Galleons, Sickles, and Knuts, then returns a new Vault initialized with those totals.

    Explanation

    The overloaded + lets the caller write potter + weasley instead of manually calculating each denomination.

  66. 66

    Can a class's __add__ method be defined to accept a right operand of a different type?

    Model answer

    It can accept another type, but the method's implementation must define what that combination means and handle the other type's data appropriately.

    Explanation

    The content notes that the right operand can be another type in principle, though an unsupported combination may fail when the method tries to use incompatible attributes.

  67. 67

    Can Python programmers invent entirely new operator symbols, or do they overload existing operators?

    Model answer

    They overload operators from the language's available set; the content does not describe a way to invent arbitrary new operator symbols.

    Explanation

    Python provides a defined set of special methods corresponding to existing operators.

  68. 68

    Besides addition, what kinds of operators can be overloaded?

    Model answer

    Many existing operators can be overloaded, including comparison and augmented-assignment operators such as less-than, plus-equals, and minus-equals.

    Explanation

    The content points to a broad list of special methods corresponding to common operators.

  69. 69

    What does the type function reveal about a value, and how can it be used during exploration?

    Model answer

    It reports the value's type, which can help a programmer inspect what kind of object a value is.

    Explanation

    The content demonstrates checking the types of integer, string, list, and dictionary values.

  70. 70

    What do integers, strings, lists, and dictionaries have in common in Python's object model?

    Model answer

    Each is an instance of a built-in class, and each can be created as an object of that type.

    Explanation

    The content emphasizes that built-in data types are classes, even though they were used before that terminology was introduced.

  71. 71

    How can an empty list or an empty dictionary be created using its class name?

    Model answer

    An empty list can be created with list(), and an empty dictionary with dict().

    Explanation

    These are alternatives to the empty-list literal [] and empty-dictionary literal {}.

  72. 72

    What is a built-in method, and what familiar string methods are mentioned?

    Model answer

    A built-in method is behavior provided by a class for its objects. String methods mentioned include lower and strip.

    Explanation

    lower changes a string to lowercase, while strip removes leading and trailing whitespace.

  73. 73

    What familiar list method is mentioned, and what does it do?

    Model answer

    The append method adds an item to a list.

    Explanation

    Calling this method operates on the current list object and adds the supplied value.

  74. 74

    What naming convention is recommended for programmer-defined Python classes, and how does it contrast with the built-in names discussed?

    Model answer

    Programmer-defined class names conventionally begin with a capital letter, while built-in names such as int, str, and list are lowercase.

    Explanation

    The content presents capitalization as a Python community convention for custom classes, not a requirement for the built-in classes.

  75. 75

    Why may a programmer choose a class rather than a module, package, or standalone functions to organize a program?

    Model answer

    A class can bundle related data and behavior under a named type, which may improve organization as a program becomes more complex.

    Explanation

    The content presents classes, modules, packages, and local files as organizational tools whose suitability depends on the problem.

1 of 75
Question 1 of 75

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent