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

  • 95Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Programming Paradigms
  • spaceFlip card
  • KI knew it
  • DI didn't know it
  • ←Previous card
  • →Next card

What is a programming paradigm?

Tap to flipClick to flipspace

A general approach or style for solving problems with code.

Or swipe the card

95 cards

  1. What is a programming paradigm?

    A general approach or style for solving problems with code.

  2. What characterizes procedural programming?

    Programs are organized around procedures or functions that perform steps in sequence, often from top to bottom.

  3. What is functional programming, as introduced in the lesson?

    A programming approach that includes treating functions as values that can be passed around, including using anonymous functions.

  4. What problem does object-oriented programming help address as programs grow?

    It helps organize increasingly large and complicated programs by grouping related data and functionality.

  5. What does object-oriented programming let a programmer define?

    Custom data types, along with data and functionality associated with those types.

  6. What does it mean to encapsulate functionality in a class?

    To keep functionality related to a type of object together inside that type’s class.

  7. Why might a class be preferable to a standalone function or a collection of general-purpose values?

    A class can group related data and behavior, improve organization, and provide mechanisms for checking data correctness.

  8. What is a common heuristic for deciding what a class might represent?

    A class often models an entity from the real world or a fictional world, though this is not a requirement.

  9. What is a tuple in Python?

    An ordered collection of values that is immutable.

  10. How can a Python function return a tuple containing two values?

    Return the values separated by a comma, optionally enclosing them in parentheses, such as return name, house.

  11. When Python code returns name, house, how many objects does it return?

    One tuple containing two values, rather than two separate return objects.

  12. How can a returned tuple be unpacked into separate variables?

    Assign it to a matching sequence of variables, such as name, house = get_student().

  13. How do you access the first and second values of a tuple or list?

    Use numeric indexing with square brackets: index 0 for the first value and index 1 for the second.

  14. Why might a tuple be preferable to a list when storing values?

    Use a tuple when the values should not change; its immutability can help prevent accidental modifications and bugs.

  15. What happens if you try to assign a new value to an element of a tuple?

    Python raises a TypeError because tuples do not support item assignment.

  16. How does a list differ from a tuple?

    A list is mutable, so its elements can be changed; a tuple is immutable.

  17. How do the literal forms of a list and tuple differ?

    Lists are created with square brackets; tuples are commonly written with comma-separated values, often inside parentheses.

  18. How do you index into a list or tuple?

    Use square brackets with a numeric index, even though the literal forms of lists and tuples differ.

  19. What is a Python dictionary?

    A mutable collection of key-value pairs.

  20. How does dictionary lookup differ from list or tuple lookup?

    Dictionaries are accessed by keys, often strings; lists and tuples are accessed by numeric indices.

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

    Keys such as name and house describe the values, so the code does not depend on remembering which numeric position stores each value.

  22. Can Python lists and tuples contain nested collections or different kinds of values?

    Yes. They can contain values such as other lists, strings, or integers; tuples can contain lists too, although the tuple itself remains immutable.

  23. What is a class in Python?

    A definition or blueprint for creating objects of a custom data type.

  24. What does the class keyword do?

    It defines a class, which can be used as a blueprint for creating objects.

  25. What is an object in relation to a class?

    An object is an instance, or a specific instantiation, of a class.

  26. How are a class and an object related to a blueprint and a built item?

    The class is the blueprint or mold; an object is a specific item created from it.

  27. What is the usual naming convention for a programmer-defined Python class?

    Capitalize the first letter of the class name, as in Student; many built-in type names, such as int and list, are lowercase.

  28. How do you create an object of a class named Student?

    Call the class name like a function, for example student = Student().

  29. What is an attribute of an object?

    A value associated with an object and accessed using dot notation, such as student.name.

  30. What is an instance variable?

    A variable stored on a particular object, commonly assigned through self, such as self.name.

  31. What is a method?

    A function defined inside a class.

  32. What is the purpose of the special __init__ method?

    It initializes an object’s contents when the object is created.

  33. What does self refer to inside an instance method?

    The current object on which the method is operating.

  34. Why does an instance method conventionally list self as its first parameter?

    Python passes the current object to the method so it can access or modify that object’s attributes.

  35. In __init__(self, name, house), why are self.name = name and self.house = house used?

    They store the supplied name and house values as instance variables on the newly initialized object.

  36. What is the distinction between __new__ and __init__?

    __new__ creates an empty object; __init__ initializes its contents. Python generally handles __new__ automatically, so programmers usually define __init__.

  37. What is a constructor call in the lesson’s terminology?

    Calling a class, such as Student(name, house), to create and initialize an object.

  38. Can an __init__ method accept optional arguments?

    Yes. Parameters can have default values, allowing callers to omit them.

  39. What does a class’s default string representation typically show if it has no custom __str__ method?

    A technical representation that includes the object’s type and a reference to its location in memory.

  40. What is the purpose of the special __str__ method?

    It defines a human-readable string representation of an object, such as the one used by print.

  41. What does Python pass to an object’s __str__ method?

    A reference to the object being converted to a string, conventionally received as self.

  42. How does __str__ differ from __repr__ in the lesson?

    __str__ is generally intended to be user-friendly; __repr__ is generally intended for developers and may include more technical detail.

  43. Why can validating data in __init__ alone be insufficient?

    The object’s attributes may still be changed after initialization, potentially bypassing the original validation.

  44. What does it mean to raise an exception in Python?

    To signal that an error or exceptional condition has occurred, allowing calling code to handle it if appropriate.

  45. How can a programmer raise a ValueError with an explanatory message?

    Use raise ValueError("message"), such as raise ValueError("missing name").

  46. Why might raising an exception be preferable to calling sys.exit for invalid input?

    An exception signals the error without forcibly terminating the entire program, so the caller can handle it.

  47. How can a programmer handle an exception raised while creating an object?

    Use try and except around the operation, catching an appropriate exception type.

  48. What is a property in Python?

    An attribute with added behavior or validation, commonly implemented with getter and setter methods.

  49. What does the @property decorator do?

    It marks a method as a getter so it can be accessed like an attribute.

  50. What does a property getter do, and how many parameters does it conventionally declare?

    It returns the property’s value; it conventionally declares only self.

  51. How is a setter for a property named house declared?

    Use @house.setter above a method also named house, conventionally with parameters self and the new value.

  52. Why does a property setter take an additional argument beyond self?

    It needs the value that the caller is trying to assign to the property.

  53. How can a property setter prevent an invalid house value?

    Check whether the value belongs to the allowed set and raise a ValueError if it does not.

  54. Why can assigning self.house = house inside __init__ be useful when a house property exists?

    The assignment invokes the property setter, allowing initialization to use the same validation as later assignments.

  55. Why is an underscore often prefixed to a property’s backing instance variable?

    To distinguish the backing variable, such as _house, from the property named house and avoid a name collision.

  56. Does a leading underscore make an instance variable truly private in Python?

    No. It is a convention asking programmers not to access it directly; Python does not enforce privacy in the same way as some languages.

  57. What does a double leading underscore generally signal by convention?

    An even stronger request that programmers avoid touching the variable, though it is not absolute privacy.

  58. What is the difference between an instance method and a class method?

    An instance method operates on a particular object and receives self; a class method operates in relation to the class and receives the class itself.

  59. How is a class method declared in Python?

    Place @classmethod above the method definition.

  60. What is the conventional first parameter of a class method?

    cls, a reference to the class itself.

  61. What is a class variable?

    A variable defined on the class itself and shared by its objects, rather than stored separately on each instance.

  62. How does accessing a class variable differ from accessing an instance variable?

    A class variable is associated with the class, such as Hat.houses; an instance variable is associated with an object, such as student.name.

  63. When can a class method be useful instead of an instance method?

    When the operation relates to the class as a whole and does not require a particular object’s instance data.

  64. Why might a sorting-hat operation be implemented as a class method?

    If the sorting behavior and house list belong to the Sorting Hat concept rather than to distinct hat objects, there is no need to instantiate a hat.

  65. How can a class method construct an object of its own class?

    It can call cls(...), using the class reference automatically passed to the method.

  66. Why might a class method be used to get or create a student?

    It can gather the required information and create a student without first needing an existing student object.

  67. What is a static method, and how is it marked?

    It is another kind of class-contained method; it is marked with @staticmethod and does not receive self or cls automatically.

  68. What is inheritance?

    A feature that lets one class derive from another and reuse its attributes and methods.

  69. What are a subclass and a superclass?

    A subclass inherits from a superclass, which is also called its parent class.

  70. How is inheritance specified in a Python class definition?

    Put the superclass in parentheses after the subclass name, such as class Student(Wizard):.

  71. Why might students and professors inherit from a shared Wizard class?

    They share common functionality, such as storing and validating a name, which can be implemented once in the superclass.

  72. How can a subclass invoke its superclass’s __init__ method?

    Call super().__init__(...), passing the arguments needed by the superclass initializer.

  73. Why use super().__init__ in a subclass initializer?

    It reuses the superclass’s initialization behavior, such as assigning shared attributes and performing shared validation.

  74. Can a class inherit functionality through more than one level of a hierarchy?

    Yes. A class can inherit functionality from ancestors higher in the hierarchy, not only its immediate superclass.

  75. Can a subclass override inherited behavior?

    Yes. A subclass can provide its own version of inherited functionality.

  76. What is operator overloading?

    Defining how familiar operators, such as +, behave for objects of a custom class.

  77. How has Python already overloaded the + operator for different types?

    For example, + can add numbers, concatenate strings, or combine lists.

  78. Which special method supports overloading the + operator?

    __add__.

  79. What arguments does __add__ conventionally receive?

    self, representing the left operand, and another argument, often named other, representing the right operand.

  80. What happens when Python evaluates left + right for a class that defines __add__?

    Python calls the left operand’s __add__ method with the right operand as the other argument.

  81. How could a Vault class define addition of two vaults?

    Implement __add__ to add their corresponding coin counts and return a new Vault containing the totals.

  82. What determines whether adding a vault to a different type is meaningful?

    The implementation of the left operand’s __add__ method determines how to handle the other operand; the operation may be meaningless or raise an error.

  83. Can a programmer define arbitrary new operator symbols in Python?

    No. Python provides a set of existing operators that can be overloaded; programmers cannot create arbitrary new operator characters.

  84. Besides +, can other operators be overloaded?

    Yes. Many existing operators, including comparison and compound-assignment operators, have corresponding special methods.

  85. What programming concepts have Python’s built-in types already been using?

    Built-in types such as integers, strings, lists, and dictionaries are classes; their values are objects with methods and other class-defined behavior.

  86. What does the type() function reveal about a value?

    It reports the value’s type, which corresponds to its class.

  87. What is the relationship between int and integer values in Python?

    int is a class; converting a value to an integer creates an object of that class.

  88. What is the relationship between str and string values in Python?

    str is a class, and string values are objects of that class.

  89. What are lower() and strip() examples of?

    They are methods provided by the string class: lower() changes case, while strip() removes leading and trailing whitespace.

  90. What is the relationship between list and list values?

    list is a class; list literals and calls such as list() create list objects.

  91. What is append() in relation to lists?

    It is a list method that adds an item to the list.

  92. What is the relationship between dict and dictionary values?

    dict is a class; dictionary literals and calls such as dict() create dictionary objects.

  93. Why are built-in types such as int, str, list, and dict written in lowercase while custom class names are commonly capitalized?

    Python’s built-in types use lowercase names, while the convention for programmer-defined classes is to capitalize the first letter.

  94. What does a class hierarchy among exceptions allow Python to do?

    Specific exception types can inherit shared behavior from broader exception classes, and handlers can catch a parent type to handle multiple related exceptions.

  95. How can a programmer define a custom exception?

    Define a new exception class, typically inheriting from an existing exception class, and add any needed custom behavior.

Card 1 of 95
Card 1 of 95

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent