1. Home
  2. Explore
  3. Computer Science
  4. Python OOP Course

Study methods

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

Python OOP Course

  • 63Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Classes and Instances

How do you define a class in Python?

63 questions

  1. 1

    How do you define a class in Python?

    Model answer

    Use the class keyword followed by the class name and a colon, e.g., class Item:.

    Explanation

    The class keyword is used to define a new class, which serves as a blueprint for creating objects.

  2. 2

    How do you create an instance of a class?

    Model answer

    Call the class like a function: instance = ClassName().

    Explanation

    This creates a new instance (object) of the class, similar to how you create a string or integer.

  3. 3

    What is an attribute in the context of a class?

    Model answer

    An attribute is a variable that belongs to an instance or class, used to store data related to the object.

    Explanation

    Attributes are accessed using dot notation, e.g., item.name = 'Phone'.

  4. 4

    What is the difference between using four separate variables and using a class with attributes to represent an item?

    Model answer

    With a class, the attributes are related to a single instance, whereas separate variables are independent and Python sees no relationship between them.

    Explanation

    A class groups related data into one object, while individual variables are just separate pieces of data with no logical connection.

  5. 5

    What does type(item1) show if item1 is an instance of a custom class Item?

    Model answer

    It shows <class '__main__.Item'> indicating that item1 is an object of the Item class.

    Explanation

    Each instance has a type that is the class it was instantiated from, similar to how strings have the type str.

  6. 6

    What is a method in a class?

    Model answer

    A method is a function defined inside a class that operates on instances of that class.

    Explanation

    Methods are accessed via the instance and receive the instance itself as the first argument, conventionally named self.

  7. 7

    Why must every method in a class have at least one parameter?

    Model answer

    Because Python automatically passes the instance itself as the first argument when the method is called on an instance.

    Explanation

    If a method has zero parameters, Python raises a TypeError because it tries to pass one argument (the instance) but the method does not accept it.

  8. 8

    What is the conventional name for the first parameter of a method?

    Model answer

    self.

    Explanation

    Although any name works, self is the standard convention and should always be used for readability.

  9. 9

    How do you call a method on an instance?

    Model answer

    Use dot notation: instance.method().

    Explanation

    This calls the method with the instance automatically passed as the first argument.

  10. 10

    What error occurs if you define a method without any parameters and then call it on an instance?

    Model answer

    TypeError: method() takes 0 positional arguments but 1 was given.

    Explanation

    Python tries to pass the instance as an argument, but the method does not accept any.

  11. 11

    How do you access instance attributes inside a method?

    Model answer

    Use self.attribute_name.

    Explanation

    The self parameter refers to the instance, so any attribute stored on the instance can be accessed via self.

  12. 12

    What is the __init__ method?

    Model answer

    It is the constructor method that is automatically called when an instance is created.

    Explanation

    __init__ initializes the instance, often by assigning initial values to attributes.

  13. 13

    How does __init__ receive parameters?

    Model answer

    It receives self as the first parameter, followed by any additional arguments passed when creating the instance.

    Explanation

    For example, item1 = Item('Phone', 100, 5) passes three arguments, which are received by __init__ as self, name, price, quantity.

  14. 14

    How do you assign attributes dynamically inside __init__?

    Model answer

    Use self.attribute = parameter, e.g., self.name = name.

    Explanation

    This sets the attribute on the instance, allowing each instance to have its own values.

  15. 15

    Why is self used in __init__?

    Model answer

    self refers to the instance being created, so assigning to self.attribute stores the attribute on that specific instance.

    Explanation

    Without self, the attribute would be a local variable and not attached to the instance.

  16. 16

    How do you give a parameter in __init__ a default value?

    Model answer

    Assign a default value in the parameter list, e.g., quantity=0.

    Explanation

    Default values make parameters optional – if not provided, the default is used.

  17. 17

    What is a type hint in a method parameter?

    Model answer

    It is a syntax like name: str that indicates the expected type of the parameter.

    Explanation

    Type hints are not enforced at runtime but are used by IDEs and linters for code quality.

  18. 18

    How does a type hint affect code behavior?

    Model answer

    It does not enforce the type; it only provides documentation and IDE support.

    Explanation

    Python is dynamically typed, so type hints are optional and do not prevent passing wrong types.

  19. 19

    What is the assert statement used for?

    Model answer

    To check a condition and raise an AssertionError if the condition is False.

    Explanation

    Assertions are useful for debugging and validating assumptions, e.g., ensuring prices are non-negative.

  20. 20

    How do you add a custom error message to an assert statement?

    Model answer

    assert condition, 'message' – the message is displayed if the assertion fails.

    Explanation

    The message helps identify the cause of the failure, e.g., 'Price is not greater than zero'.

  21. 21

    Why are assertions used in constructors?

    Model answer

    To catch invalid data early, preventing the creation of instances with incorrect attribute values.

    Explanation

    Assertions ensure that the object is in a valid state from the start.

  22. 22

    What is a class attribute?

    Model answer

    An attribute that belongs to the class itself, shared by all instances.

    Explanation

    Class attributes are defined directly inside the class body, outside any methods.

  23. 23

    How do you define a class attribute?

    Model answer

    Assign a value to a variable inside the class definition, e.g., pay_rate = 0.8.

    Explanation

    This attribute is stored on the class object and is accessible to all instances.

  24. 24

    How do you access a class attribute?

    Model answer

    Via the class name (ClassName.attribute) or via an instance (instance.attribute).

    Explanation

    When accessed via an instance, Python first looks for the attribute on the instance; if not found, it looks on the class.

  25. 25

    What happens if an instance tries to access an attribute that does not exist on the instance but exists on the class?

    Model answer

    The attribute is retrieved from the class, so the value is shared across all instances.

    Explanation

    This lookup behavior allows class attributes to serve as defaults for all instances.

  26. 26

    How can you override a class attribute for a specific instance?

    Model answer

    Assign a new value to the attribute on the instance: instance.attribute = new_value.

    Explanation

    This creates an instance attribute that shadows the class attribute for that particular instance.

  27. 27

    What is the __dict__ attribute of an object?

    Model answer

    It is a dictionary containing all instance attributes of the object.

    Explanation

    __dict__ shows the attributes directly attached to the instance, not inherited class attributes.

  28. 28

    How can you see all instance attributes of an object?

    Model answer

    Use print(object.__dict__).

    Explanation

    This is useful for debugging to see what attributes an object currently has.

  29. 29

    What is the difference between a class attribute and an instance attribute?

    Model answer

    A class attribute is shared by all instances; an instance attribute is unique to each instance.

    Explanation

    Class attributes are defined on the class, instance attributes are defined on the instance (often in __init__).

  30. 30

    What is a class method?

    Model answer

    A method that receives the class as the first argument instead of the instance.

    Explanation

    Class methods are decorated with @classmethod and are often used for factory methods that create instances from different data sources.

  31. 31

    What decorator is used to define a class method?

    Model answer

    @classmethod.

    Explanation

    The decorator must be placed directly before the method definition.

  32. 32

    What is the first parameter of a class method conventionally named?

    Model answer

    cls.

    Explanation

    cls refers to the class itself, not an instance.

  33. 33

    When should you use a class method?

    Model answer

    When you need to create instances from structured data like CSV or JSON files.

    Explanation

    Class methods are ideal for alternative constructors that don't operate on an existing instance.

  34. 34

    How do you create a class method that reads a CSV file and creates instances?

    Model answer

    Use @classmethod and a method that opens the CSV, reads it with csv.DictReader, and instantiates the class for each row.

    Explanation

    The class method can access the class via cls to create new instances with cls(name=..., price=..., quantity=...).

  35. 35

    What is a static method?

    Model answer

    A method that does not receive an automatic first argument (neither instance nor class).

    Explanation

    Static methods behave like regular functions but are namespaced within the class.

  36. 36

    What decorator is used for a static method?

    Model answer

    @staticmethod.

    Explanation

    It tells Python that the method does not need a special first parameter.

  37. 37

    When would you use a static method?

    Model answer

    For utility functions that are related to the class but do not depend on instance or class state, e.g., checking if a number is an integer.

    Explanation

    Static methods are placed inside the class for organizational purposes but lack access to self or cls.

  38. 38

    What is the main difference between a class method and a static method?

    Model answer

    A class method receives cls (the class) as first argument; a static method receives no automatic arguments.

    Explanation

    Class methods can access or modify class state; static methods cannot.

  39. 39

    Can class methods and static methods be called from an instance?

    Model answer

    Yes, but it is not recommended; they are intended to be called from the class.

    Explanation

    Calling them from an instance works but can be confusing and is rarely needed.

  40. 40

    What is inheritance in OOP?

    Model answer

    A mechanism where a child class derives properties and methods from a parent class.

    Explanation

    Inheritance promotes code reuse and establishes a hierarchy.

  41. 41

    How do you define a child class that inherits from a parent class?

    Model answer

    Use class Child(Parent): with the parent class in parentheses.

    Explanation

    The child class automatically gains all methods and attributes of the parent.

  42. 42

    What is a parent class?

    Model answer

    The class that is being inherited from, also called a base class.

    Explanation

    The parent class provides common functionality that child classes can use or override.

  43. 43

    What is a child class?

    Model answer

    A class that inherits from another class, also called a subclass.

    Explanation

    The child class can extend or modify the behavior of the parent.

  44. 44

    What does a child class inherit from its parent?

    Model answer

    All methods and attributes (including class attributes) of the parent class.

    Explanation

    Unless overridden, the child class uses the parent's implementations.

  45. 45

    How do you call the parent class constructor from a child class?

    Model answer

    Use super().__init__(args) inside the child's __init__ method.

    Explanation

    This ensures the parent's initialization code runs, avoiding duplication.

  46. 46

    Why is using super() important?

    Model answer

    It provides access to parent methods and attributes without hardcoding the parent class name, making code more maintainable.

    Explanation

    super() also handles multiple inheritance correctly.

  47. 47

    What is the __repr__ method?

    Model answer

    A magic method that returns a string representation of an object, ideally one that can recreate the object.

    Explanation

    __repr__ is used for debugging and logging; it should be unambiguous.

  48. 48

    How should you implement __repr__?

    Model answer

    Return a formatted string like f"{self.__class__.__name__}('{self.name}', {self.price}, {self.quantity})".

    Explanation

    Using self.__class__.__name__ makes the representation generic for inheritance.

  49. 49

    What is polymorphism?

    Model answer

    The ability of a single entity (function, method, operator) to work with different data types.

    Explanation

    For example, the len() function returns the length for strings, lists, etc.

  50. 50

    Give an example of polymorphism in Python.

    Model answer

    The len() function works on strings, lists, tuples, dictionaries, etc.

    Explanation

    Polymorphism allows the same function name to handle different object types appropriately.

  51. 51

    How does inheritance enable polymorphism?

    Model answer

    Child classes can use parent methods, and the same method can work for different child classes.

    Explanation

    For example, calling apply_discount() on a Phone instance and a Keyboard instance both work if the method is defined in the parent class.

  52. 52

    How can you override a class attribute in a child class?

    Model answer

    Define the same attribute name in the child class with a different value.

    Explanation

    The child's attribute shadows the parent's attribute for instances of the child class.

  53. 53

    What is encapsulation?

    Model answer

    Restricting direct access to an object's attributes and providing controlled access via methods.

    Explanation

    Encapsulation protects the internal state and prevents unintended modifications.

  54. 54

    How do you create a read-only attribute in Python?

    Model answer

    Use the @property decorator on a method that returns the attribute value, without a setter.

    Explanation

    This makes the attribute accessible but not assignable from outside the class.

  55. 55

    What is a getter?

    Model answer

    A method decorated with @property that returns the value of an attribute.

    Explanation

    Getters allow reading the attribute while hiding its internal implementation.

  56. 56

    What is a setter?

    Model answer

    A method decorated with @attribute.setter that allows modifying an attribute, often with validation.

    Explanation

    Setters provide controlled write access, e.g., checking length or range.

  57. 57

    What is a private attribute in Python?

    Model answer

    An attribute with a double underscore prefix (e.g., __price), which triggers name mangling to make it harder to access from outside the class.

    Explanation

    Private attributes are still accessible via _ClassName__attribute, but the convention signals they are internal.

  58. 58

    How does using double underscore affect external access?

    Model answer

    The attribute name is mangled to _ClassName__attribute, so direct access without mangling fails.

    Explanation

    This discourages accidental external modification but is not a security measure.

  59. 59

    What is abstraction?

    Model answer

    Hiding complex implementation details and exposing only essential features to the user.

    Explanation

    Abstraction simplifies interaction with objects by providing a clear interface.

  60. 60

    How do you create a private method?

    Model answer

    Prefix the method name with double underscore: def __method(self):.

    Explanation

    Private methods are intended for internal use only and are name-mangled like private attributes.

  61. 61

    Why use private methods?

    Model answer

    To hide internal implementation details and prevent them from being called from outside the class.

    Explanation

    This supports abstraction by keeping the public interface clean.

  62. 62

    What is the purpose of getters and setters?

    Model answer

    To control how attributes are accessed and modified, allowing validation or side effects.

    Explanation

    They enforce encapsulation by acting as intermediaries for attribute access.

  63. 63

    How can you enforce validation in a setter?

    Model answer

    Check the value inside the setter and raise an exception or reject invalid values.

    Explanation

    For example, check if the new value is within an expected range before assigning.

1 of 63
Question 1 of 63

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent