Object-Oriented Programming in Python
- 95Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
- spaceFlip card
- KI knew it
- DI didn't know it
- ←Previous card
- →Next card
What is a programming paradigm?
A general approach or style for solving problems with code.
Or swipe the card
95 cards
What is a programming paradigm?
A general approach or style for solving problems with code.
What characterizes procedural programming?
Programs are organized around procedures or functions that perform steps in sequence, often from top to bottom.
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.
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.
What does object-oriented programming let a programmer define?
Custom data types, along with data and functionality associated with those types.
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.
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.
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.
What is a tuple in Python?
An ordered collection of values that is immutable.
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.When Python code returns
name, house, how many objects does it return?One tuple containing two values, rather than two separate return objects.
How can a returned tuple be unpacked into separate variables?
Assign it to a matching sequence of variables, such as
name, house = get_student().How do you access the first and second values of a tuple or list?
Use numeric indexing with square brackets: index
0for the first value and index1for the second.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.
What happens if you try to assign a new value to an element of a tuple?
Python raises a
TypeErrorbecause tuples do not support item assignment.How does a list differ from a tuple?
A list is mutable, so its elements can be changed; a tuple is immutable.
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.
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.
What is a Python dictionary?
A mutable collection of key-value pairs.
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.
Why can a dictionary be clearer than a tuple for storing a student's name and house?
Keys such as
nameandhousedescribe the values, so the code does not depend on remembering which numeric position stores each value.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.
What is a class in Python?
A definition or blueprint for creating objects of a custom data type.
What does the
classkeyword do?It defines a class, which can be used as a blueprint for creating objects.
What is an object in relation to a class?
An object is an instance, or a specific instantiation, of a class.
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.
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 asintandlist, are lowercase.How do you create an object of a class named
Student?Call the class name like a function, for example
student = Student().What is an attribute of an object?
A value associated with an object and accessed using dot notation, such as
student.name.What is an instance variable?
A variable stored on a particular object, commonly assigned through
self, such asself.name.What is a method?
A function defined inside a class.
What is the purpose of the special
__init__method?It initializes an object’s contents when the object is created.
What does
selfrefer to inside an instance method?The current object on which the method is operating.
Why does an instance method conventionally list
selfas its first parameter?Python passes the current object to the method so it can access or modify that object’s attributes.
In
__init__(self, name, house), why areself.name = nameandself.house = houseused?They store the supplied
nameandhousevalues as instance variables on the newly initialized object.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__.What is a constructor call in the lesson’s terminology?
Calling a class, such as
Student(name, house), to create and initialize an object.Can an
__init__method accept optional arguments?Yes. Parameters can have default values, allowing callers to omit them.
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.
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.What does Python pass to an object’s
__str__method?A reference to the object being converted to a string, conventionally received as
self.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.Why can validating data in
__init__alone be insufficient?The object’s attributes may still be changed after initialization, potentially bypassing the original validation.
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.
How can a programmer raise a
ValueErrorwith an explanatory message?Use
raise ValueError("message"), such asraise ValueError("missing name").Why might raising an exception be preferable to calling
sys.exitfor invalid input?An exception signals the error without forcibly terminating the entire program, so the caller can handle it.
How can a programmer handle an exception raised while creating an object?
Use
tryandexceptaround the operation, catching an appropriate exception type.What is a property in Python?
An attribute with added behavior or validation, commonly implemented with getter and setter methods.
What does the
@propertydecorator do?It marks a method as a getter so it can be accessed like an attribute.
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.How is a setter for a property named
housedeclared?Use
@house.setterabove a method also namedhouse, conventionally with parametersselfand the new value.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.
How can a property setter prevent an invalid house value?
Check whether the value belongs to the allowed set and raise a
ValueErrorif it does not.Why can assigning
self.house = houseinside__init__be useful when ahouseproperty exists?The assignment invokes the property setter, allowing initialization to use the same validation as later assignments.
Why is an underscore often prefixed to a property’s backing instance variable?
To distinguish the backing variable, such as
_house, from the property namedhouseand avoid a name collision.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.
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.
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.How is a class method declared in Python?
Place
@classmethodabove the method definition.What is the conventional first parameter of a class method?
cls, a reference to the class itself.What is a class variable?
A variable defined on the class itself and shared by its objects, rather than stored separately on each instance.
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 asstudent.name.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.
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.
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.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.
What is a static method, and how is it marked?
It is another kind of class-contained method; it is marked with
@staticmethodand does not receiveselforclsautomatically.What is inheritance?
A feature that lets one class derive from another and reuse its attributes and methods.
What are a subclass and a superclass?
A subclass inherits from a superclass, which is also called its parent class.
How is inheritance specified in a Python class definition?
Put the superclass in parentheses after the subclass name, such as
class Student(Wizard):.Why might students and professors inherit from a shared
Wizardclass?They share common functionality, such as storing and validating a name, which can be implemented once in the superclass.
How can a subclass invoke its superclass’s
__init__method?Call
super().__init__(...), passing the arguments needed by the superclass initializer.Why use
super().__init__in a subclass initializer?It reuses the superclass’s initialization behavior, such as assigning shared attributes and performing shared validation.
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.
Can a subclass override inherited behavior?
Yes. A subclass can provide its own version of inherited functionality.
What is operator overloading?
Defining how familiar operators, such as
+, behave for objects of a custom class.How has Python already overloaded the
+operator for different types?For example,
+can add numbers, concatenate strings, or combine lists.Which special method supports overloading the
+operator?__add__.What arguments does
__add__conventionally receive?self, representing the left operand, and another argument, often namedother, representing the right operand.What happens when Python evaluates
left + rightfor a class that defines__add__?Python calls the left operand’s
__add__method with the right operand as the other argument.How could a
Vaultclass define addition of two vaults?Implement
__add__to add their corresponding coin counts and return a newVaultcontaining the totals.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.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.
Besides
+, can other operators be overloaded?Yes. Many existing operators, including comparison and compound-assignment operators, have corresponding special methods.
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.
What does the
type()function reveal about a value?It reports the value’s type, which corresponds to its class.
What is the relationship between
intand integer values in Python?intis a class; converting a value to an integer creates an object of that class.What is the relationship between
strand string values in Python?stris a class, and string values are objects of that class.What are
lower()andstrip()examples of?They are methods provided by the string class:
lower()changes case, whilestrip()removes leading and trailing whitespace.What is the relationship between
listand list values?listis a class; list literals and calls such aslist()create list objects.What is
append()in relation to lists?It is a list method that adds an item to the list.
What is the relationship between
dictand dictionary values?dictis a class; dictionary literals and calls such asdict()create dictionary objects.Why are built-in types such as
int,str,list, anddictwritten 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.
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.
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.

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