Python Forum
Implement Python Class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Implement Python Class
#1
Implement the class Whatsit as defined below.

A Whatsit object should have 3 attributes:

  • level = a string defining a level of Whatsit. The allowed values of Whatsit level are 'Grooch', 'Throve', and 'Plaguelet'. If an invalid level string is supplied when constructing a Whatsit instance then a ValueError exception should be raised with a message string of 'Invalid Whatsit level'.
    name = a string, being the name of the Whatsit
    health = Current health, as a float. If a negative health value is given, a value of zero should be used instead.

A Whatsit instance can be created using calls such as the following:

fester = Whatsit('Throve', 'Walter', 10.500)
poxer = Whatsit('Plaguelet', 'Angus', 0.100)


Whatsits should have the following methods:

__str__ method

This method should return a string representation of the Whatsit's details. For example, assuming fester is as defined above:
fester.__str__() should return the string

'Walter (Throve), health = 10.5'

Health is always displayed with one decimal digit of precision.

ouch method

The ouch method takes a value for the amount of health that is lost due to the inflicted suffering and reduces the Whatsit's health by that amount. If health falls below zero then health should be set to the minimum value, which is 0.

The examples below should give you more of an idea of how the Whatsit class should be defined.

Test Code 1:
fester = Whatsit('Throve', 'Walter', 10.500)
print(fester)
Expected Output:
Walter (Throve), health = 10.5
Test Code 2:
fester = Whatsit('Throve', 'Walter', 10.491)
print(fester)
fester.ouch(10.4)
print(fester)
fester.ouch(2)
print(fester)
Output:

Walter (Throve), health = 10.5
Walter (Throve), health = 0.1
Walter (Throve), health = 0.0
Test Code 3:
try:
    oof = Whatsit('Famine', 'Fred', 0)
    print(oof)
except ValueError as e:
    print(e)
Expected Output:
Invalid Whatsit level
Reply
#2
What have you tried? Show your code in python tags and ask specific questions. We are glad to help, but we are not going to write it for you.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using the robot class - implement robot battles - Python OOP krnkrnkrn 1 1,895 May-17-2021, 09:19 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020