Python (Modern Python 3 Bootcamp, Sections 24-27, OOP/Iterators/Generators)

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

If you want a Cat class to inherit from an Animal class, how would that be written? A) class Cat extends Animal: B) class Cat(Animal): C) class Cat inherits from Animal: D) none of the above

B

next(iter("Oprah")) returns what? A) TypeError B) IteratorError C) "O" D) "o"

C

Super is the preferred way to reference the parent since it follows _______ automatically.

MRO

What does MRO stand for?

Method Resolution Order

True or False: All generators are iterators.

True

Properties, in general, allow you to access class __________ without the need for methods like get_age().

attributes

A generator function returns a(n) _____________, which is a(n) _______________.

generator iterator

class Cat(Animal): blue = Cat() Write *three different* isinstance() statements that would all return True for blue.

isinstance(blue, Cat) isinstance(blue, Animal) isinstance(blue, object)

A single underscore (_name) is used to denote __________ attributes/methods. A double underscore (__name) is used for ______ __________. A double-double underscore, aka "dunder", (__name__) is only used when referencing or ______________ something used by Python.

private name mangling overriding

You want to define a setter without defining a set_age() method. i.e., you want to be able to set an instance's age using simply... jane.age = 20 How would you do that?

@age.setter def age(self, val): self._age = val

Class methods are decorated with the _______________ decorator.

@classmethod

In general, using the _______________ decorator is better/simpler than using a getter.

@property

If you want to instantiate a class Pet that takes in a name and a species, how would you do it? A) dog = Pet("Fluffy", "dog") B) dog = new Pet("Fluffy", "dog")

A

In Python, inheritance works by... A) passing the parent class as an argument to the definition of the child class B) passing the child class as an argument to the definition of the parent

A

Inside a class User with a class method from_string() that takes in name and age, you want to create a new user. How do you do this? A) return cls(name, age) B) return User(name, age)

A

What function is used to iterate through an iterator? A) next() B) then() C) get() D) none of the above

A

Which one of these is NOT a difference between a function and a generator function? A) Functions are declared with the def keyword; generator functions are not. B) Functions can return only one value; generator functions can return multiple values. C) Functions use the return keyword; generator functions use the yield keyword. D) Generator functions always return a generator; functions may not.

A

class Penguin(Ambulatory, Aquatic) uses multiple inheritance. Which class "takes priority" over the other class (in terms of __init__(), identical method names, etc)? A) Ambulatory B) Aquatic

A

You're going to find the sum of all numbers from 1 to 10,000,000. Which of the following would be faster? Why? A) sum(n for n in range(10000000)) B) sum([n for n in range(10000000)])

A In this case, generator expressions/object are much faster because it doesn't have to create an entire list of numbers from 1 to 10,000,000 before *then* going back and adding them all up. No list is ever created, which saves quite a bit of time.

"Poly" means many, and "morph" means shapes or forms, so in regards to OOP, what would "polymorphism" mean?

An object can take on many forms.

What does it mean when we say an iterator "can be iterated upon"?

Anything we could run a for loop on

In a class Person with an attribute __msg, instantiated with person1, how will Python make that attribute accessible via name mangling? A) person1.__msg B) person1._Person__msg

B

Strings/lists/etc -- on their own -- are what? A) iterators B) iterables

B

The __repr__() is a: A) class method, taking in cls as the first param B) instance method, taking in self as the first param

B

Which of the following is *NOT* an iterable? A) "123" B) 123 C) [1, 2, 3] D) (1, 2, 3)

B

class Pet(Animal, Friend): def __init__(self, name) self.name = name What is the best way to call the parent __init__ methods? A) In the init method, Animal.__init__ and Friend.__init B) In the init method, call super().__init__

B

dict.fromkeys() is a great real-world example of a(n) A) instance method B) class method

B

If you're defining a class, and you want all instances to have an attribute called "count" that *always* starts at zero, how should your __init__() method be set up? A) include count in both the params and body B) include count in the params, but set the default to zero and do *not* include it in the body C) include count in the body, setting it to zero, but do *not* include it in the params D) include count in neither the params nor the body, making a Class attribute instead

C

The MRO is actually very complex, but you can see any class's MRO via three different methods. Which one is the most readable for humans? A) __mro__ attribute on a class B) use the mro() method on the class C) use the built-in help(cls) method

C

Which of the following is NOT true? A) Generators are iterators B) Generators can be created with generator functions C) Generators functions use the "generate" keyword D) Generators can be created with generator expressions

C (Generator functions use the "yield" keyword)

The MRO is actually very complex, but how can you programmatically reference it? A) __mro__ attribute on a class B) use the mro() method on the class C) use the built-in help(cls) method D) all of the above

D

What is MRO in Python? A) The order in which you define methods on a class. B) The order in which the parent methods are defined. C) The order in which Python resolves functions. D) The order in which Python looks up/resolves methods on a class, influenced by inheritance.

D

What's the difference between a class method and an instance method? A) A class method has the class (cls) as the implicit first argument, while an instance method has the instance (self). B) Class methods must be decorated with @classmethod, while instance methods do not. C) Class methods are used when the method does not need to know about the specific instance; instance methods are the opposite. D) All of the above

D

True or False: All iterators are generators.

False

True or False: If you want an instance method that doesn't require self (just prints "hello", for example), then you *don't* need to define self as a parameter to that method.

False

True or False: Lists are always slower than generators.

False

True or False: Multiple inheritance is used quite often in Python OOP.

False

True or False: Python supports scope with the traditional public/protected/private methods and properties.

False

True or False: You can only refer to class attributes via ClassName.attribute, *not* through any instances via instance_name.attribute

False (Python is somewhat unique in this way.)

True or False: You use parentheses when defining a class. class Person():

False (Unless the class is inheriting from a parent class.)

True or False: The __init__() method must *always* have "self" as the first parameter (even though you don't pass anything in for its value), and it must *always* be named "self"?

False It must be there, but it can be named whatever. But basically always developers will name it "self".

If you were going to model out a poker application using OOP, what are seven possible classes that could include?

Game Player Card Deck Hand Chip Bet

Whenever you create a class, Python sets a __________, which is the order in which Python will look for methods on instances of that class.

MRO

True or False: Class attributes/methods are used *far* less often than instance attributes/methods.

True

True or False: Everything in Python inherits from the base "object" class.

True

True or False: Lists take up more memory than generators.

True

True or False: Once you call next() on a generator, there is no "going back." Whatever value is yielded from the first next() can only be captured again by instantiating a new instance of the generator object.

True

True or False: There is no such thing as a private attribute/method in Python.

True

True or False: Whenever we call next() on something, it must be an iterator. Therefore, next("Oprah") would throw a TypeError.

True

True or False: You can set up a class that inherits from a base class like dict or str. Ex: class GrumpyDict(dict):

True

True or False: Using the @property decorator removes the need to use parentheses on simple getters.

True @property def age(self): return self._age print(something.age)

True or False: Lists/strings/etc are never actually directly looped over.

True The for loop calls iter(string/list/etc), which returns an iterator, which the loop calls next() on to loop through.

If you wanted to be able to "add" two instances of a class together using the + operator, how could you do that?

Write a new __add__() method in the class.

How could you override the built-in len() method inside a class?

Write a new __len__() method that does whatever you want.

You have a class Pet with a class attribute allowed, which is a list of strings for allowed species of a pet. Two instances of been instantiated, dog and cat. id(Pet.allowed) id(dog.allowed) id(cat.allowed) Are all three of these equal?

Yes

The + operator is actually a shorthand representation of what "magic method"?

__add__()

What class method will Python look for (and call, if it's there) every time you instantiate that class?

__init__

By default, printing an instance of a class results in something ugly like... <__main__.User object at 0x471389471> How can this be overridden?

__repr__()

What method is Python using "behind the scenes" when we print out a list or dictionary to make it more readable for us?

__repr__()

____________ is the idea of exposing only the relevant data in a class, hiding private attributes/methods (the "inner workings") from users.

abstraction

Classes are ______________ for objects.

blueprints

The convention for naming classes: 1) Use the keyword _________ 2) Use __________Case 3) Use ____________ (singular/plural)

class Camel singular

Instance methods are probably used 50-100 times more often than ____________ _______________.

class methods

OOP is a method of programming that attempts to model some process or thing in the world as a ___________ or ___________.

class or object

Instance methods always need to take in self as the first param, since Python needs access to that instance. Class methods, on the other hand, always need to take in ___________ as the first param.

cls

With OOP, the goal is to _______________ your code into *logical, hierarchical groupings (using classes)* so that you can reason about your code at a higher level.

encapsulate

_______________ is the grouping of public and private attributes and methods into a class, making _____________ possible.

encapsulation abstraction

def nums(): for num in range(1, 10): yield num g = nums() g is now a generator object. However, how could you have accomplished the same thing *without* ever defining nums()?

g = (num for num in range(1, 10))

If you write a function and use yield anywhere (where you might've used return instead), it will give a _______________ _______________ by default when you call/execute it.

generator object

A key feature of OOP is _______________, which gives us the ability to define a class that inherits from another class (a "base" or "parent" class).

inheritance

In general, name mangling (__msg) is used to avoid conflicts that could arise during class ___________________.

inheritance

You only write class methods if you don't need access to any data regarding a particular ______________.

instance

Inside a class User... self.count would refer to the _________________. User.count would refer to the _______________.

instance class

Class attributes/methods (as opposed to instance attributes/methods), are defined directly on a class and are shared by all ______________ of that class as well as the class itself.

instances

Objects that are constructed from a class blueprint and contain that class's methods and properties are called ____________.

instances

Fill in the blanks with "iterable", "iterator" and "iter". The ______() function returns an ____________ on an _____________.

iter() iterator iterable

An _____________ is an object that returns an iterator (when iter() is called on it).

iterable

An _____________ (iterator or iterable) is any object that can be iterated upon.

iterator

A for loop basically turns whatever is passed to it into an ___________ using __________. It continues calling next() until a _______________ error is thrown.

iterator iter() StopIteration

In short, a generator is a way of creating _______________ very quickly.

iterators (You don't have to define __iter__(), __next__(), etc.)

Generator expressions are to generators what __________ _________________ are to lists.

list comprehensions

If you're dealing with really large datasets that, if you stored in a list, that list would grow massive, generators are a better option because they take up far less _____________.

memory

The two most important practical applications of polymorphism are: 1) The same class __________ works in a different way for different classes. 2) The same ____________ works for different kinds of objects.

method (Cat.speak(), Dog.speak(), Human.speak(), etc) operation (len(some_list), len(some_tuple), len(some_string), etc)

Behind the scenes of for loops, there is a method called _________(), which returns the next item in the iterator.

next()

Generator functions return a generator object, which you can call _________() on to yield each subsequent value.

next()

Generator expressions use ___________ in place of list comprehension's brackets.

parentheses

The fact that len() works on different kinds of objects like lists, strings, tuples, etc, is a practical example of _______________.

polymorphism

The fact that a subclass can have a method that overrides a method of the same name in its parent class ("method overriding") is a practical example of ______________ & _______________.

polymorphism & inheritance

The __repr__() method stands for what?

representation

The _______ keyword refers to the current instance of the class.

self

When defining *any* instance method, _________ must *always* be the first parameter.

self

If one class inherits from another, what method is used inside its __init__() to prevent having to redefine any of the same attributes?

super()

class Cat(Animal): If Animal has two attributes -- name and species -- that are inherited in Cat, what method is used inside Cat's __init__() to assign those attributes without code duplication?

super() def __init__(self, name, species, something_else): super().__init__(name, species="Cat") self.something_else = something_else

If you want to call a parent class's "magic" __repr__() method (or any other parent class method), it must be preceded by __________________.

super(). super().__repr__()

Python's "self" is basically equivalent to PHP/Javascript/other language's _______.

this

Traditionally, class attributes are defined at the _________ of the class and called using the ___________ name instead of an instance.

top class

What is the syntax for making something "private" in Python (i.e., to signal to other developers that the method/property shouldn't be exposed)?

underscore _cards _max_cards

Normal functions use the return keyword, return only once, and -- when invoked -- return the return value. Generator functions use the _________ keyword, return _________ ___________, and -- when invoked -- return a ____________.

yield multiple times generator


Kaugnay na mga set ng pag-aaral

Chapter 60: Assessment of Integumentary Function

View Set

World's Ten Most Populous Countries (Week 27)

View Set

Colder than Here - Scene Revision

View Set

Intermediate 1 Hindi USA final exam

View Set

Psychology unit 1 test (ch.1 & 2)

View Set