For printing the oxygen and nitrogen, you would do:
class Lifesupport(object):
def __init__(self, oxygen, nitrogen):
self.oxygen = oxygen
self.nitrogen = nitrogen
def __str__(self):
return "Your air has {0}% oxygen and {1}% nitrogen".format(self.oxygen, self.nitrogen)
Then later, whenever you want to show the Lifesupport
levels, you simply do:
air = Lifesupport(40, 60)
print(air)
The __str__
method overrides the default __str__
method of a class and so when you do print(air)
, it will print the custom text.
As for class vs. method, it is recommended that you use classes, especially when you know that are going to be expanding your program, since you can create multiple instances of a class that will all have attributes that can be modified independent of each other. Below is an example:
Example
class A:
def __init__(self,num):
self.val = num
a = A(4)
b = A(5)
>>> print(a.val)
4
>>> a.val = 6
>>> print(a.val)
6
>>> print(b.val)
5