Deck 10: Object-Oriented Programming  

Full screen (f)
exit full mode
Question
When you evaluate a variable in IPython it calls the corresponding object's ________ special method to produce a string representation of the object.

A) __init__
B) __str__
C) __string__
D) xe "object class:__repr__ special method"xe "__repr__ special method of class object[repr__ special method of class object]"__repr__
Use Space or
up arrow
down arrow
to flip the card.
Question
Which of the following statements a), b) or c) is false?

A) Everything in Python is an object.
B) Just as houses are built from blueprints, classes are built from objects-one of the core technologies of object-oriented programming.
C) Building a new object from even a large class is simple-you typically write one statement.
D) All of the above statements are true.
Question
Which of the following statements is false?

A) The following xe "constructor expression"constructor expression creates a new object, then initializes its data by calling the class's __init__ method:
Account1 = Account('John Green', Decimal('50.00'))
B) Each new class you create can provide an __init__ method that specifies how to initialize an object's xe "class:data attribute"xe "data:attribute of a class"data attributes.
C) Returning a value other than Null from __init__ results in a TypeError. Null is returned by any function or method that does not contain a return statement.
D) Class Account's __init__ method below initializes an Account object's name and balance attributes if the balance is valid:
Def __init__(self, name, balance):
"""Initialize an Account object."""
# if balance is less than 0.00, raise an exception
If balance < Decimal('0.00'):
Raise ValueError('Initial balance must be >= to 0.00.')
Self.name = name
Self.balance = balance
Question
Which of the following statements a), b) or c) is false?

A) You'll use lots of classes created by other people.
B) You can create your own custom classes.
C) Core technologies of object-oriented programming are classes, objects, inheritance and polymorphism.
D) All of the above statements are true.
Question
Which of the following statements a), b) or c) is false?

A) Classes are new function types.
B) Most applications you'll build for your own use will commonly use either no custom classes or just a few.
C) You can contribute your custom classes to the Python open-source community, but you are not obligated to do so. Organizations often have policies and procedures related to open-sourcing code.
D) All of the above statements are true.
Question
Which of the following statements is false?

A) Methods commonly use a class's attributes to get the values of those attributes.
B) We also can use a class's attributes to modify their values.
C) Consider the Account object in the following IPython session:
In [1]: from account import Account
In [2]: from decimal import Decimal
In [3]: account1 = Account('John Green', Decimal('50.00'))
In [4]: account1.balance
Out[4]: Decimal('50.00')
Initially, account1 contains a valid balance. The following code shows that we can set the balance attribute to an invalid negative value, then display the balance:
In [5]: account1.balance = Decimal('-1000.00')
In [6]: account1.balance
Out[6]: Decimal('-1000.00')
D) Like methods, data attributes can validate the values you assign to them.
Question
Each new class you create becomes a new data type that can be used to create objects. This is one reason why Python is said to be a(n) ________ language.

A) dynamic typing
B) comprehensive
C) extensible
D) None of the above
Question
Which of the following statements a), b) or c) is false?

A) Polymorphism enables you to conveniently xe "program "in the general""program "in the general" rather than "xe "program "in the specific""in the specific."
B) With polymorphism, you simply send the same method call to objects possibly of many different types. Each object responds by "doing the right thing" for objects of its type. So the same method call takes on many forms, hence the term "poly-morphism."
C) In Python, as in other major object-oriented programming languages, you can implement polymorphism only via inheritance.
D) All of the above statements are true.
Question
Properties look like ________ to client-code programmers, but control the manner in which they get and modify an object's data.

A) function calls
B) method calls
C) data attributes
D) None of the above
Question
Which of the following statements is false?

A) A class definition begins with the keyword class followed by the class's name and a colon (:). This line is called the class header.
B) The xe "Style Guide for Python Code:class names"Style Guide for Python Code recommends that you begin each word in a multi-word class name with an uppercase letter (e.g., CommissionEmployee).
C) Every statement in a class's suite is indented.
D) Each class must provide a descriptive xe "docstring:for a class"docstring in the line or lines immediately following the xe "class:header"class header. To view any class's docstring in IPython, type the class name and a question mark, then press Enter.
Question
Which of the following statements is false?

A) New classes can be formed quickly through inheritance and composition from classes in abundant class libraries.
B) Eventually, software will be constructed predominantly from standardized, xe "reusable componentry"reusable xe "component"components, just as hardware is constructed from interchangeable parts today. This will help meet the challenges of developing ever more powerful software.
C) When creating a new class, instead of writing all new code, you can designate that the new class is to be formed initially by inheriting the attributes and methods of a previously defined base class (also called a subclass) and the new class is called a derived class (or superclass).
D) After inheriting, you then customize the derived class to meet the specific needs of your application. To minimize the customization effort, you should always try to inherit from the base class that's closest to your needs.
Question
Python class ________ defines the special methods that are available for all Python objects.

A) object
B) special
C) class
D) root
Question
Assume that class Time's __init__ method receives hour, minute and second parameters. Based on the following code: wake_up = Time(hour=6, minute=30)
Which of the following statements is true?

A) If at least two arguments have default arguments, the third automatically defaults to zero.
B) Any omitted argument is automatically set to zero.
C) second has a default argument in the __init__ method's definition.
D) None of the above.
Question
To create a Decimal object, we can write: value = Decimal('3.14159')
This is known as a(n) ________ expression because it builds and initializes an object of the class.

A) builder
B) maker
C) assembler
D) constructor
Question
An object's attributes are references to objects of other classes. Embedding references to objects of other classes is a form of software reusability known as ________ and is sometimes referred to as the ________ relationship.

A) composition, "is a"
B) inheritance, "has a"
C) composition, "has a"
D) inheritance, "is a"
Question
Most object-oriented programming languages enable you to encapsulate (or hide) an object's data from the client code. Such data in these languages is said to be ________ data.

A) public
B) protected
C) private
D) None of the above
Question
Which of the following statements is false?

A) The vast majority of object-oriented programming you'll do in Python is object-based programming in which you primarily use objects of new custom classes you create.
B) To take maximum advantage of Python you must familiarize yourself with lots of preexisting classes.
C) Over the years, the Python open-source community has crafted an enormous number of valuable classes and packaged them into class libraries, available on the Internet at sites like xe "GitHub"GitHub, xe "BitBucket"BitBucket, xe "SourceForge"SourceForge and more. This makes it easy for you to reuse existing classes rather than "reinventing the wheel."
D) Widely used open-source library classes are more likely to be thoroughly tested, bug free, performance tuned and portable across a wide range of devices, operating systems and Python versions.
Question
Which of the following statements a), b) or c) is false?

A) When you call a method for a specific object, Python implicitly passes a reference to that object as the method's first argument, so all methods of a class must specify at least one parameter.
B) All methods must have a first parameter xe "self in a method's parameter list"self-a class's methods must use that reference to access the object's attributes and other methods.
C) When an object of a class is created, it does not yet have any attributes. They're added dynamically via assignments, typically of the form self.attribute_name = value.
D) All of the above statements are true.
Question
Which of the following statements about code snippets that use class Account is false?

A) The following code uses a constructor expression to create an Account object and initialize it with an account holder's name (a string) and balance (a Decimal):
Account1 = Account('John Green', Decimal('50.00'))
B) The following expressions access an Account object's name and balance xe "class:attribute"xe "attribute:of a class"xe "attribute:of a class"attributes:
Account1.name
Account1.balance
C) The following snippets deposit an amount into an Account and access the new balance:
Account1.deposit(Decimal('25.53'))
Account1.balance
D) All of the above statements are true.
Question
Which of the following statements a), b) or c) is false?

A) Python does not have private data. Instead, you use xe "naming convention:for encouraging correct use of attributes"naming conventions to design classes that encourage correct use.
B) An attribute name beginning with an underscore (_) is never accessible by clients of a class.
C) Client code should use the class's methods and properties to interact with each object's internal-use data attributes.
D) All of the above statements are true.
Question
Consider the following class Time __init__ method: def __init__(self, hour=0, minute=0, second=0):
"""Initialize each attribute."""
Self.hour = hour # 0-23
Self.minute = minute # 0-59
Self.second = second # 0-59
Which of the following statements a), b) or c) is false?

A) Class Time's __init__ method specifies hour, minute and second parameters, each with a default argument of 0.
B) The self parameter is a reference to the Time object being initialized.
C) The statements containing self.hour, self.minute and self.second appear to create hour, minute and second attributes for the new Time object (self). However, these statements may actually call methods that implement the class's hour, minute and second properties.
D) All of the above statements are true.
Question
The ________ special method is called implicitly when you convert an object to a string with the built-in function xe "built-in function:str"xe "str built-in function"str, such as when you print an object or call xe "built-in function:str"xe "str built-in function"str explicitly.

A) __repr__
B) __string__
C) __str__
D) None of the above
Question
Which of the following statements a), b) or c) is false?

A) Each property defines a getter method which gets (that is, returns) a data attribute's value and can optionally define a setter method which sets a data attribute's value.
B) The @property decorator precedes a property's xe "getter method:decorator"getter method, which receives only a self parameter.
C) Behind the scenes, a decorator adds code to the decorated function to enable the function to work with data attribute syntax.
D) All of the above statements are true.
Question
Which of the following statements about a class's utility methods is false?

A) They serve as part of a class's interface.
B) They are used inside the class.
C) They should be named with a single leading underscore.
D) In other object-oriented languages like C++, Java and C#, utility methods typically are implemented as private methods.
Question
Which of the following statements a), b) or c) is false?

A) It may seem that providing properties with both setters and getters has no benefit over accessing the data attributes directly, but there are subtle differences.
B) A getter seems to allow clients to read the data at will, but the getter can control the formatting of the data.
C) A setter can scrutinize attempts to modify the value of a data attribute to prevent the data from being set to an invalid value.
D) All of the above statements are true.
Question
Which of the following statements a), b) or c) is false?

A) Base classes tend to be "more specific" and subclasses "more general."
B) Because every subclass object is an object of its base class, and one base class can have many subclasses, the set of objects represented by a base class is often larger than the set of objects represented by any of its subclasses.
C) The base class Vehicle represents all vehicles, including cars, trucks, boats, bicycles and so on. Subclass Car represents a smaller, more specific subset of vehicles.
D) All of the above statements are true.
Question
Which of the following statements a), b) or c) is false?

A) A base class exists in a hierarchical relationship with its subclasses.
B) With single inheritance, a class is derived from one base class. With multiple inheritance, a subclass inherits from two or more base classes.
C) One reason to avoid multiple inheritance is the "diamond problem in Python multiple inheritance."
D) All of the above statements are true.
Question
Which of the following statements is false?

A) Sometimes, an attribute should be shared by all objects of a class. A class attribute (also called a class variable) represents class-wide information-it belongs to the class, not to a specific object of that class.
B) You define a class attribute by assigning a value to it inside the class's definition, but not inside any of the class's methods or properties (in which case, they'd be local variables).
C) Class attributes are typically accessed through any object of the class.
D) Class attributes exist as soon as you import their class's definition.
Question
Which of the following statements is false?

A) Python provides two built-in functions-issubclass and isinstance-for testing "is a" relationships.
B) Function issubclass determines whether one class inherits from another.
C) Function isinstance determines whether an object has an "is a" relationship with a specific type.
D) If SalariedCommissionEmployee inherits from CommissionEmployee, and if object s is a SalariedCommissionEmployee, then the following snippet results are correct:
In [19]: isinstance(s, CommissionEmployee)
Out[19]: False
In [20]: isinstance(s, SalariedCommissionEmployee)
Out[20]: True
Question
Consider the following code from our class Time: @property
Def hour(self):
"""Return the hour."""
Return self._hour
@hour.setter
Def hour(self, hour):
"""Set the hour."""
If not (0 <= hour < 24):
Raise ValueError(f'Hour ({hour}) must be 0-23')
Self._hour = hour

A) This code defines a read-write property named hour that manipulates a data attribute named _hour.
B) The xe "naming convention:single leading underscore"xe "single leading underscore naming convention"single-leading-underscore (_) naming convention indicates that client code can safely access _hour directly.
C) Properties look like data attributes to programmers working with objects. Properties are implemented as methods.
D) All of the above statements are true.
Question
Which of the following statements a), b) or c) is false?

A) A class can also support setting its attribute values individually via its properties. Assuming hour is a property of wake_up's class, the following statement changes an hour property value to 6:
Wake_up.hour = 6
B) Though the statement snippet in Part (a) appears to simply assign a value to a data attribute, it's actually a call to an hour method that takes 6 as an argument.
C) The hour method mentioned in Part (b) can validate the value, then assign it to a corresponding data attribute (which we might name _hour, for example).
D) Each of the above statements is true.
Question
A read-only property has ________.

A) only a setter
B) only a getter
C) a setter and a getter
D) neither a setter nor a getter
Question
Consider the following code which would set the hour of a Time object to an invalid value. wake_up._hour = 100
Which of the following statements is false?

A) Rather than _hour, we can name the attribute __hour with two leading underscores. This convention indicates that __hour is "private" and should not be accessible to the class's xe "client of a class"clients.
B) To help prevent clients from accessing "private" attributes, Python renames them by preceding the attribute name with _ClassName, as in _Time__hour. This is called xe "name mangling"name mangling.
C) If you try to assign to __hour, as in
Wake_up.__hour = 100
Python raises a ValueError, indicating that the class does not have an __hour attribute.
D) IPython does not show attributes with one or two leading underscores when you try to auto-complete an expression like
Wake_up.
By pressing Tab. Only attributes that are part of the wake_up object's "public" interface are displayed in the IPython auto-completion list.
Question
Properties are implemented as ________, so they may contain additional logic, such as specifying the format in which to return a data attribute's value or validating a new value before using it to modify a data attribute.

A) functions
B) suites
C) classes
D) methods
Question
The following code and traceback shows that our class Time's hour property xe "validate data"validates the values you assign to it: In [10]: wake_up.hour = 100
---------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
----> 1 wake_up.hour = 100
~/Documents/examples/ch10/timewithproperties.py in hour(self, hour)
20 """Set the hour."""
21 if not (0 <= hour < 24):
---> 22 raise ValueError(f'Hour ({hour}) must be 0-23')
23
24 self._hour = hour
ValueError: Hour (100) must be 0-23
Which of the following statements a), b) or c) is false?

A) The code attempts to set the hour property to an invalid value.
B) The code checks that the hour property is in the range 0 through 24.
C) The value 100 is out of range so the code raises a ValueError.
D) All of the above statements are true.
Question
Which of the following statements a), b) or c) is false?

A) When you design a class, carefully consider the class's interface before making that class available to other programmers.
B) Unfortunately, existing code will break if you update the class's implementation details-that is, the internal data representation or how its method bodies are implemented.
C) If Python programmers follow convention and do not access attributes that begin with leading underscores, then class designers can evolve class implementation details without breaking client code.
D) All of the above statements are true.
Question
Class Time's properties and methods define the class's ________ interface, that is, the properties and methods programmers should use to interact with objects of the class.

A) public
B) private
C) protected
D) None of the above
Question
Which of the following statements a), b) or c) is false?

A) With inheritance, every object of a subclass also may be treated as an object of that subclass's base class.
B) We can take advantage of this xe ""derived-class-object-is-a-base-class-object" relationship[derived class object is a base class object relationship]""subclass-object-is-a-base-class-object" relationship to place objects related through inheritance into a xe "list of base-class objects"list, then iterate through the list and treat each element as a base-class object.
C) The following code places CommissionEmployee and SalariedCommissionEmployee objects (c and s) in a list, then for each element displays its string representation and earnings-this is an example of xe "polymorphism"polymorphism:
In [21]: employees = [c, s]
In [22]: for employee in employees:
)..: print(employee)
)..: print(f'{employee.earnings():,.2f}\n')
)..:
CommissionEmployee: Sue Jones
Social security number: 333-33-3333
Gross sales: 20000.00
Commission rate: 0.10
2,000.00
SalariedCommissionEmployee: Bob Lewis
Social security number: 444-44-4444
Gross sales: 10000.00
Commission rate: 0.05
Base salary: 1000.00
1,500.00
D) All of the above statements are true.
Question
Which of the following statements is false?

A) Often, an object of one class is an object of another class as well.
B) A CarLoan is a Loan as are HomeImprovementLoans and MortgageLoans. Class CarLoan can be said to inherit from class Loan.
C) In the context of Part (b), class CarLoan is a base class, and class Loan is a subclass.
D) In the context of Part (b) a CarLoan is a specific type of Loan, but it's incorrect to claim that every Loan is a CarLoan-the Loan could be any type of loan.
Question
Which of the following statements a), b) or c) is false?

A) When you pass an object to built-in function xe "built-in function:repr"xe "repr built-in function"repr-which happens implicitly when you evaluate a variable in an IPython session-the corresponding class's __repr__ special method is called to get the "official" string representation of the object.
B) Typically the string returned by __repr__ looks like a constructor expression that creates and initializes the object, such as:
'Time(hour=6, minute=30, second=0)'
C) Python has a built-in function eval that could receive the string shown in Part (b) as an argument and use it to create and initialize a Time object containing values specified in the string.
D) All of the above statements are true.
Question
Which of the following statements a), b) or c) is false?
B) All classes inherit from object directly or indirectly, so they all inherit the default methods for obtaining string representations that print can display.
B) Python also has duck typing, which the Python documentation describes as: A programming style which does not look at an object's type to determine if it has the right interface; instead, the method or attribute is simply called or used ("If it looks like a duck and quacks like a duck, it must be a duck.").
C) When Python processes an object at execution time, its type does not matter. As long as the object has the data attribute, property or method (with the appropriate parameters) you wish to access, the code will work.
D) All of the above statements are true.
Question
Consider the following loop, which processes a list of employees: for employee in employees:
Print(employee)
Print(f'{employee.earnings():,.2f}\n')
Which of the following statements a), b) or c) is false?

A) In Python, this loop works properly as long as employees contains only objects that can be displayed with print (that is, they have a string representation)
B) All classes inherit from object directly or indirectly, so they all inherit the default methods for obtaining string representations that print can display.
C) If a class has an earnings method that can be called with no arguments, we can include objects of that class in the list employees, even if the object's class does not have an "is a" relationship with class CommissionEmployee.
D) All of the above statements are true.
Unlock Deck
Sign up to unlock the cards in this deck!
Unlock Deck
Unlock Deck
1/42
auto play flashcards
Play
simple tutorial
Full screen (f)
exit full mode
Deck 10: Object-Oriented Programming  
1
When you evaluate a variable in IPython it calls the corresponding object's ________ special method to produce a string representation of the object.

A) __init__
B) __str__
C) __string__
D) xe "object class:__repr__ special method"xe "__repr__ special method of class object[repr__ special method of class object]"__repr__
D
2
Which of the following statements a), b) or c) is false?

A) Everything in Python is an object.
B) Just as houses are built from blueprints, classes are built from objects-one of the core technologies of object-oriented programming.
C) Building a new object from even a large class is simple-you typically write one statement.
D) All of the above statements are true.
B
3
Which of the following statements is false?

A) The following xe "constructor expression"constructor expression creates a new object, then initializes its data by calling the class's __init__ method:
Account1 = Account('John Green', Decimal('50.00'))
B) Each new class you create can provide an __init__ method that specifies how to initialize an object's xe "class:data attribute"xe "data:attribute of a class"data attributes.
C) Returning a value other than Null from __init__ results in a TypeError. Null is returned by any function or method that does not contain a return statement.
D) Class Account's __init__ method below initializes an Account object's name and balance attributes if the balance is valid:
Def __init__(self, name, balance):
"""Initialize an Account object."""
# if balance is less than 0.00, raise an exception
If balance < Decimal('0.00'):
Raise ValueError('Initial balance must be >= to 0.00.')
Self.name = name
Self.balance = balance
C
4
Which of the following statements a), b) or c) is false?

A) You'll use lots of classes created by other people.
B) You can create your own custom classes.
C) Core technologies of object-oriented programming are classes, objects, inheritance and polymorphism.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
5
Which of the following statements a), b) or c) is false?

A) Classes are new function types.
B) Most applications you'll build for your own use will commonly use either no custom classes or just a few.
C) You can contribute your custom classes to the Python open-source community, but you are not obligated to do so. Organizations often have policies and procedures related to open-sourcing code.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
6
Which of the following statements is false?

A) Methods commonly use a class's attributes to get the values of those attributes.
B) We also can use a class's attributes to modify their values.
C) Consider the Account object in the following IPython session:
In [1]: from account import Account
In [2]: from decimal import Decimal
In [3]: account1 = Account('John Green', Decimal('50.00'))
In [4]: account1.balance
Out[4]: Decimal('50.00')
Initially, account1 contains a valid balance. The following code shows that we can set the balance attribute to an invalid negative value, then display the balance:
In [5]: account1.balance = Decimal('-1000.00')
In [6]: account1.balance
Out[6]: Decimal('-1000.00')
D) Like methods, data attributes can validate the values you assign to them.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
7
Each new class you create becomes a new data type that can be used to create objects. This is one reason why Python is said to be a(n) ________ language.

A) dynamic typing
B) comprehensive
C) extensible
D) None of the above
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
8
Which of the following statements a), b) or c) is false?

A) Polymorphism enables you to conveniently xe "program "in the general""program "in the general" rather than "xe "program "in the specific""in the specific."
B) With polymorphism, you simply send the same method call to objects possibly of many different types. Each object responds by "doing the right thing" for objects of its type. So the same method call takes on many forms, hence the term "poly-morphism."
C) In Python, as in other major object-oriented programming languages, you can implement polymorphism only via inheritance.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
9
Properties look like ________ to client-code programmers, but control the manner in which they get and modify an object's data.

A) function calls
B) method calls
C) data attributes
D) None of the above
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
10
Which of the following statements is false?

A) A class definition begins with the keyword class followed by the class's name and a colon (:). This line is called the class header.
B) The xe "Style Guide for Python Code:class names"Style Guide for Python Code recommends that you begin each word in a multi-word class name with an uppercase letter (e.g., CommissionEmployee).
C) Every statement in a class's suite is indented.
D) Each class must provide a descriptive xe "docstring:for a class"docstring in the line or lines immediately following the xe "class:header"class header. To view any class's docstring in IPython, type the class name and a question mark, then press Enter.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
11
Which of the following statements is false?

A) New classes can be formed quickly through inheritance and composition from classes in abundant class libraries.
B) Eventually, software will be constructed predominantly from standardized, xe "reusable componentry"reusable xe "component"components, just as hardware is constructed from interchangeable parts today. This will help meet the challenges of developing ever more powerful software.
C) When creating a new class, instead of writing all new code, you can designate that the new class is to be formed initially by inheriting the attributes and methods of a previously defined base class (also called a subclass) and the new class is called a derived class (or superclass).
D) After inheriting, you then customize the derived class to meet the specific needs of your application. To minimize the customization effort, you should always try to inherit from the base class that's closest to your needs.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
12
Python class ________ defines the special methods that are available for all Python objects.

A) object
B) special
C) class
D) root
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
13
Assume that class Time's __init__ method receives hour, minute and second parameters. Based on the following code: wake_up = Time(hour=6, minute=30)
Which of the following statements is true?

A) If at least two arguments have default arguments, the third automatically defaults to zero.
B) Any omitted argument is automatically set to zero.
C) second has a default argument in the __init__ method's definition.
D) None of the above.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
14
To create a Decimal object, we can write: value = Decimal('3.14159')
This is known as a(n) ________ expression because it builds and initializes an object of the class.

A) builder
B) maker
C) assembler
D) constructor
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
15
An object's attributes are references to objects of other classes. Embedding references to objects of other classes is a form of software reusability known as ________ and is sometimes referred to as the ________ relationship.

A) composition, "is a"
B) inheritance, "has a"
C) composition, "has a"
D) inheritance, "is a"
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
16
Most object-oriented programming languages enable you to encapsulate (or hide) an object's data from the client code. Such data in these languages is said to be ________ data.

A) public
B) protected
C) private
D) None of the above
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
17
Which of the following statements is false?

A) The vast majority of object-oriented programming you'll do in Python is object-based programming in which you primarily use objects of new custom classes you create.
B) To take maximum advantage of Python you must familiarize yourself with lots of preexisting classes.
C) Over the years, the Python open-source community has crafted an enormous number of valuable classes and packaged them into class libraries, available on the Internet at sites like xe "GitHub"GitHub, xe "BitBucket"BitBucket, xe "SourceForge"SourceForge and more. This makes it easy for you to reuse existing classes rather than "reinventing the wheel."
D) Widely used open-source library classes are more likely to be thoroughly tested, bug free, performance tuned and portable across a wide range of devices, operating systems and Python versions.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
18
Which of the following statements a), b) or c) is false?

A) When you call a method for a specific object, Python implicitly passes a reference to that object as the method's first argument, so all methods of a class must specify at least one parameter.
B) All methods must have a first parameter xe "self in a method's parameter list"self-a class's methods must use that reference to access the object's attributes and other methods.
C) When an object of a class is created, it does not yet have any attributes. They're added dynamically via assignments, typically of the form self.attribute_name = value.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
19
Which of the following statements about code snippets that use class Account is false?

A) The following code uses a constructor expression to create an Account object and initialize it with an account holder's name (a string) and balance (a Decimal):
Account1 = Account('John Green', Decimal('50.00'))
B) The following expressions access an Account object's name and balance xe "class:attribute"xe "attribute:of a class"xe "attribute:of a class"attributes:
Account1.name
Account1.balance
C) The following snippets deposit an amount into an Account and access the new balance:
Account1.deposit(Decimal('25.53'))
Account1.balance
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
20
Which of the following statements a), b) or c) is false?

A) Python does not have private data. Instead, you use xe "naming convention:for encouraging correct use of attributes"naming conventions to design classes that encourage correct use.
B) An attribute name beginning with an underscore (_) is never accessible by clients of a class.
C) Client code should use the class's methods and properties to interact with each object's internal-use data attributes.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
21
Consider the following class Time __init__ method: def __init__(self, hour=0, minute=0, second=0):
"""Initialize each attribute."""
Self.hour = hour # 0-23
Self.minute = minute # 0-59
Self.second = second # 0-59
Which of the following statements a), b) or c) is false?

A) Class Time's __init__ method specifies hour, minute and second parameters, each with a default argument of 0.
B) The self parameter is a reference to the Time object being initialized.
C) The statements containing self.hour, self.minute and self.second appear to create hour, minute and second attributes for the new Time object (self). However, these statements may actually call methods that implement the class's hour, minute and second properties.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
22
The ________ special method is called implicitly when you convert an object to a string with the built-in function xe "built-in function:str"xe "str built-in function"str, such as when you print an object or call xe "built-in function:str"xe "str built-in function"str explicitly.

A) __repr__
B) __string__
C) __str__
D) None of the above
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
23
Which of the following statements a), b) or c) is false?

A) Each property defines a getter method which gets (that is, returns) a data attribute's value and can optionally define a setter method which sets a data attribute's value.
B) The @property decorator precedes a property's xe "getter method:decorator"getter method, which receives only a self parameter.
C) Behind the scenes, a decorator adds code to the decorated function to enable the function to work with data attribute syntax.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
24
Which of the following statements about a class's utility methods is false?

A) They serve as part of a class's interface.
B) They are used inside the class.
C) They should be named with a single leading underscore.
D) In other object-oriented languages like C++, Java and C#, utility methods typically are implemented as private methods.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
25
Which of the following statements a), b) or c) is false?

A) It may seem that providing properties with both setters and getters has no benefit over accessing the data attributes directly, but there are subtle differences.
B) A getter seems to allow clients to read the data at will, but the getter can control the formatting of the data.
C) A setter can scrutinize attempts to modify the value of a data attribute to prevent the data from being set to an invalid value.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
26
Which of the following statements a), b) or c) is false?

A) Base classes tend to be "more specific" and subclasses "more general."
B) Because every subclass object is an object of its base class, and one base class can have many subclasses, the set of objects represented by a base class is often larger than the set of objects represented by any of its subclasses.
C) The base class Vehicle represents all vehicles, including cars, trucks, boats, bicycles and so on. Subclass Car represents a smaller, more specific subset of vehicles.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
27
Which of the following statements a), b) or c) is false?

A) A base class exists in a hierarchical relationship with its subclasses.
B) With single inheritance, a class is derived from one base class. With multiple inheritance, a subclass inherits from two or more base classes.
C) One reason to avoid multiple inheritance is the "diamond problem in Python multiple inheritance."
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
28
Which of the following statements is false?

A) Sometimes, an attribute should be shared by all objects of a class. A class attribute (also called a class variable) represents class-wide information-it belongs to the class, not to a specific object of that class.
B) You define a class attribute by assigning a value to it inside the class's definition, but not inside any of the class's methods or properties (in which case, they'd be local variables).
C) Class attributes are typically accessed through any object of the class.
D) Class attributes exist as soon as you import their class's definition.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
29
Which of the following statements is false?

A) Python provides two built-in functions-issubclass and isinstance-for testing "is a" relationships.
B) Function issubclass determines whether one class inherits from another.
C) Function isinstance determines whether an object has an "is a" relationship with a specific type.
D) If SalariedCommissionEmployee inherits from CommissionEmployee, and if object s is a SalariedCommissionEmployee, then the following snippet results are correct:
In [19]: isinstance(s, CommissionEmployee)
Out[19]: False
In [20]: isinstance(s, SalariedCommissionEmployee)
Out[20]: True
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
30
Consider the following code from our class Time: @property
Def hour(self):
"""Return the hour."""
Return self._hour
@hour.setter
Def hour(self, hour):
"""Set the hour."""
If not (0 <= hour < 24):
Raise ValueError(f'Hour ({hour}) must be 0-23')
Self._hour = hour

A) This code defines a read-write property named hour that manipulates a data attribute named _hour.
B) The xe "naming convention:single leading underscore"xe "single leading underscore naming convention"single-leading-underscore (_) naming convention indicates that client code can safely access _hour directly.
C) Properties look like data attributes to programmers working with objects. Properties are implemented as methods.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
31
Which of the following statements a), b) or c) is false?

A) A class can also support setting its attribute values individually via its properties. Assuming hour is a property of wake_up's class, the following statement changes an hour property value to 6:
Wake_up.hour = 6
B) Though the statement snippet in Part (a) appears to simply assign a value to a data attribute, it's actually a call to an hour method that takes 6 as an argument.
C) The hour method mentioned in Part (b) can validate the value, then assign it to a corresponding data attribute (which we might name _hour, for example).
D) Each of the above statements is true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
32
A read-only property has ________.

A) only a setter
B) only a getter
C) a setter and a getter
D) neither a setter nor a getter
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
33
Consider the following code which would set the hour of a Time object to an invalid value. wake_up._hour = 100
Which of the following statements is false?

A) Rather than _hour, we can name the attribute __hour with two leading underscores. This convention indicates that __hour is "private" and should not be accessible to the class's xe "client of a class"clients.
B) To help prevent clients from accessing "private" attributes, Python renames them by preceding the attribute name with _ClassName, as in _Time__hour. This is called xe "name mangling"name mangling.
C) If you try to assign to __hour, as in
Wake_up.__hour = 100
Python raises a ValueError, indicating that the class does not have an __hour attribute.
D) IPython does not show attributes with one or two leading underscores when you try to auto-complete an expression like
Wake_up.
By pressing Tab. Only attributes that are part of the wake_up object's "public" interface are displayed in the IPython auto-completion list.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
34
Properties are implemented as ________, so they may contain additional logic, such as specifying the format in which to return a data attribute's value or validating a new value before using it to modify a data attribute.

A) functions
B) suites
C) classes
D) methods
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
35
The following code and traceback shows that our class Time's hour property xe "validate data"validates the values you assign to it: In [10]: wake_up.hour = 100
---------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
----> 1 wake_up.hour = 100
~/Documents/examples/ch10/timewithproperties.py in hour(self, hour)
20 """Set the hour."""
21 if not (0 <= hour < 24):
---> 22 raise ValueError(f'Hour ({hour}) must be 0-23')
23
24 self._hour = hour
ValueError: Hour (100) must be 0-23
Which of the following statements a), b) or c) is false?

A) The code attempts to set the hour property to an invalid value.
B) The code checks that the hour property is in the range 0 through 24.
C) The value 100 is out of range so the code raises a ValueError.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
36
Which of the following statements a), b) or c) is false?

A) When you design a class, carefully consider the class's interface before making that class available to other programmers.
B) Unfortunately, existing code will break if you update the class's implementation details-that is, the internal data representation or how its method bodies are implemented.
C) If Python programmers follow convention and do not access attributes that begin with leading underscores, then class designers can evolve class implementation details without breaking client code.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
37
Class Time's properties and methods define the class's ________ interface, that is, the properties and methods programmers should use to interact with objects of the class.

A) public
B) private
C) protected
D) None of the above
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
38
Which of the following statements a), b) or c) is false?

A) With inheritance, every object of a subclass also may be treated as an object of that subclass's base class.
B) We can take advantage of this xe ""derived-class-object-is-a-base-class-object" relationship[derived class object is a base class object relationship]""subclass-object-is-a-base-class-object" relationship to place objects related through inheritance into a xe "list of base-class objects"list, then iterate through the list and treat each element as a base-class object.
C) The following code places CommissionEmployee and SalariedCommissionEmployee objects (c and s) in a list, then for each element displays its string representation and earnings-this is an example of xe "polymorphism"polymorphism:
In [21]: employees = [c, s]
In [22]: for employee in employees:
)..: print(employee)
)..: print(f'{employee.earnings():,.2f}\n')
)..:
CommissionEmployee: Sue Jones
Social security number: 333-33-3333
Gross sales: 20000.00
Commission rate: 0.10
2,000.00
SalariedCommissionEmployee: Bob Lewis
Social security number: 444-44-4444
Gross sales: 10000.00
Commission rate: 0.05
Base salary: 1000.00
1,500.00
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
39
Which of the following statements is false?

A) Often, an object of one class is an object of another class as well.
B) A CarLoan is a Loan as are HomeImprovementLoans and MortgageLoans. Class CarLoan can be said to inherit from class Loan.
C) In the context of Part (b), class CarLoan is a base class, and class Loan is a subclass.
D) In the context of Part (b) a CarLoan is a specific type of Loan, but it's incorrect to claim that every Loan is a CarLoan-the Loan could be any type of loan.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
40
Which of the following statements a), b) or c) is false?

A) When you pass an object to built-in function xe "built-in function:repr"xe "repr built-in function"repr-which happens implicitly when you evaluate a variable in an IPython session-the corresponding class's __repr__ special method is called to get the "official" string representation of the object.
B) Typically the string returned by __repr__ looks like a constructor expression that creates and initializes the object, such as:
'Time(hour=6, minute=30, second=0)'
C) Python has a built-in function eval that could receive the string shown in Part (b) as an argument and use it to create and initialize a Time object containing values specified in the string.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
41
Which of the following statements a), b) or c) is false?
B) All classes inherit from object directly or indirectly, so they all inherit the default methods for obtaining string representations that print can display.
B) Python also has duck typing, which the Python documentation describes as: A programming style which does not look at an object's type to determine if it has the right interface; instead, the method or attribute is simply called or used ("If it looks like a duck and quacks like a duck, it must be a duck.").
C) When Python processes an object at execution time, its type does not matter. As long as the object has the data attribute, property or method (with the appropriate parameters) you wish to access, the code will work.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
42
Consider the following loop, which processes a list of employees: for employee in employees:
Print(employee)
Print(f'{employee.earnings():,.2f}\n')
Which of the following statements a), b) or c) is false?

A) In Python, this loop works properly as long as employees contains only objects that can be displayed with print (that is, they have a string representation)
B) All classes inherit from object directly or indirectly, so they all inherit the default methods for obtaining string representations that print can display.
C) If a class has an earnings method that can be called with no arguments, we can include objects of that class in the list employees, even if the object's class does not have an "is a" relationship with class CommissionEmployee.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 42 flashcards in this deck.
Unlock Deck
k this deck
locked card icon
Unlock Deck
Unlock for access to all 42 flashcards in this deck.