Comments (3)
Hi. This isn't really a scope issue, it's more a matter of how we're modeling the possible battery sizes for the car. Here's the get_range()
method I've shown:
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 40:
range = 150
elif self.battery_size == 65:
range = 225
print(f"This car can go about {range} miles on a full charge.")
First, range
is a local variable here, because it's only used to report the range from this method. If you want to make it an attribute by attaching it to self
, that's perfectly reasonable. But the main thing to see here is the structure of the conditional block. We only have an if-elif chain. There are only two battery sizes that work for this car: 40kWh and 65kWh.
I'm guessing your updgrade_battery()
method included an option to upgrade to 100kWh. In that case, you would have to add an additional elif block to get_range()
to report the range for that battery.
The main thing I don't like about initializing range to 0 is that it's not really meaningful. Electric cars with a functioning battery don't have a range of 0. If the owner has upgraded the battery to a size that's not recognized, the range would be unknown, not 0. That would be implemented by adding an else block that reports an unrecognized battery size.
Looking at this example again, an interesting solution gets away from if blocks. We could use a dictionary for this method:
def get_range(self):
"""Print a statement about the range this battery provides."""
# battery_ranges = {battery_size: range}
battery_ranges = {
40: 150,
65: 225
}
range = battery_ranges[self.battery_size]
print(f"This car can go about {range} miles on a full charge.")
I wouldn't say this is better or worse than the if-block approach. Some people like conditional statements, others prefer dictionary lookups. With a long set of options, the dictionary approach is probably better. Adding support for a new battery is as simple as adding a single new entry in the dictionary.
One last note; if you're staying with the conditional approach, it's good to use if-elif-else when only one of the conditions can be true. In that structure the blocks stop executing as soon as the correct match is found. In a series of simple if blocks, every check is made even if the correct one has already been found.
Does that help?
from pcc_3e.
Hi Eric,
Thank you for your wonderful analysis, yes of course using a dictionary in this scenario is wayyy better. And you were right I don't know why I declared range = 0
in the first place it doesn't mean anything when we are trying to model a real-world object using class.
Sorry for wasting your time.
from pcc_3e.
This wasn't a waste at all, it's a really interesting question that comes up when you implement an upgrade option that doesn't match what was originally written. I write a weekly newsletter about Python, and I'm going to write a post about some of the things this question raises.
I wrote this example years ago, and this is the first time I've thought to use a dictionary for the range lookup. I grew up on if statements, and didn't come across dictionaries until I started learning Python. I'm just starting to use them in place of short if-elif-else blocks.
Thanks again for reaching out!
from pcc_3e.
Related Issues (9)
- Python crash course
- pathlib.Path read_text() HOT 1
- alien_invasion: Pressing Q to Quit HOT 7
- Matplotlib installation through pip HOT 2
- pcc_3e/chapter_11 /test_name_function.py differs from text printed in book HOT 3
- Hello world! from Command Prompt Error HOT 9
- About ex_20_4_extended HOT 4
- chapter_13/ending_the_game : Ship Limit Discrepancy in Alien Invasion Game
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pcc_3e.