Unary Special Methods#
Unary operations involve only one object they are called on.
For example:
str(obj)len(obj)
only accept a single object.
This means that the corresponding special method only has self as a
parameter.
String - __str__#
When str is called on an object the Python interpreter will call the
object’s __str__ method, which must return a str value.
The returned string can be anything we choose, such as an attribute value or a formatted string combining multiple attributes together or something entirely different.
Examples
def __str__(self):
return self.name
def __str__(self):
return "{} is at your service!".format(self.name)
Length - __len__#
When len() is called on an object, Python calls the object’s __len__
method, which must return an integer.
This is typically used when the object represents a collection or something measurable.
Examples
def __len__(self):
return len(self.cargo)
def __len__(self):
return self.fuel_weight # Interpreted as fuel level
Code Challenge: Identify Yourself! Redux
The intergalactic parliament has now made it mandatory for Spaceships to identify themselves.
Complete the Spaceship class with __str__ and __repr__ methods that prints the name of the ship and the amount of fuel on board.
Requirements
Both __str__ and __repr__ methods must return a string of the form:
{name} [Fuel: {fuel_weight}/{fuel_capacity} ({fuel_percent}%)]
See example below.
The fuel_percent must be reported to 0 decimal places.
Note
Hint: You can call str(self) from __repr__ to save time.
Example
>>> xwing = Spaceship("X Wing", 500)
>>> xwing.refuel(100)
>>> print(xwing)
X Wing [Fuel: 100/500 (20%)]
>>> print(repr(xwing))
'X Wing [Fuel: 100/500 (20%)]'
Here is some code for you to start with:
class Spaceship:
def __init__(self, name, fuel_capacity):
self.name = name
self.fuel_weight = 0
self.fuel_capacity = fuel_capacity
def refuel(self, weight):
if self.fuel_weight + weight > self.fuel_capacity:
self.fuel_weight = self.fuel_capacity
else:
self.fuel_weight += weight
def fire_laser(self):
if self.fuel_weight >= 10:
self.fuel_weight -= 10
# YOUR METHODS HERE
xwing = Spaceship("X Wing", 500)
xwing.refuel(500) # Fill 'er up!
print(xwing)
Solution
Solution is locked