Make Your Own Python Text Adventure by Phillip Johnson
Author:Phillip Johnson
Language: eng
Format: epub
Publisher: Apress, Berkeley, CA
Raising Exceptions Intentionally
It may seem counter-intuitive at first, but there are some scenarios where we actually want to cause an exception to be raised. We usually do this when we want to yell at ourselves for doing something wrong! Putting in checks for bad code will help us catch errors during testing.
One vulnerability in the current code is with the Weapon class . This code would cause an exception:
1 axe = Weapon()
2 print(axe)
Why? Because the __str__() method of the Weapon class looks for a name when printing the object, but the class doesn’t have that attribute. We could fix this by assigning a name to Weapon, but that doesn’t really make sense because the class is too general to describe. Really, we should never create a Weapon object; we should always create a specific subclass like Dagger. If we need an axe object, we should create an Axe class that inherits from the superclass Weapon.
To prevent ourselves from accidentally creating Weapon objects, we can raise an exception in the initializer.
1 class Weapon:
2 def __init__(self):
3 raise NotImplementedError("Do not create raw Weapon objects.")
4
5 def __str__(self):
6 return self.name
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Deep Learning with Python by François Chollet(11873)
Hello! Python by Anthony Briggs(9365)
OCA Java SE 8 Programmer I Certification Guide by Mala Gupta(9336)
The Mikado Method by Ola Ellnestam Daniel Brolund(9300)
Dependency Injection in .NET by Mark Seemann(8853)
Algorithms of the Intelligent Web by Haralambos Marmanis;Dmitry Babenko(7845)
Test-Driven iOS Development with Swift 4 by Dominik Hauser(7305)
Grails in Action by Glen Smith Peter Ledbrook(7291)
The Well-Grounded Java Developer by Benjamin J. Evans Martijn Verburg(7111)
Secrets of the JavaScript Ninja by John Resig Bear Bibeault(5951)
Kotlin in Action by Dmitry Jemerov(4633)
Practical Vim (for Kathryn Amaral) by Drew Neil(3724)
Cracking the GRE Premium Edition with 6 Practice Tests, 2015 (Graduate School Test Preparation) by Princeton Review(3590)
Linux Device Driver Development Cookbook by Rodolfo Giometti(3388)
Learn Windows PowerShell in a Month of Lunches by Don Jones(3236)
Learning Java by Patrick Niemeyer & Daniel Leuck(2867)
Learning React: Functional Web Development with React and Redux by Banks Alex & Porcello Eve(2831)
Becoming a Dynamics 365 Finance and Supply Chain Solution Architect by Brent Dawson(2579)
Mastering Java 9 by Dr. Edward Lavieri(2569)