Modules
->
OOP
->
Case study: Time
->
Time
Time
As another example of a programmer-defined type, we'll define a class called Time that records the time of day. The class definition looks like this:
class Time: """Represents the time of day. attributes: hour, minute, second """
We can create a new Time object and assign attributes for hours, minutes, and seconds:
time = Time() time.hour = 11 time.minute = 59 time.second = 30
Instead of assigning attributes outside the class, let's define a set
method, which takes
three integers and assigns them to hour
, minute
and second
attributes:
class Time: """Represents the time of day. attributes: hour, minute, second """ def set(self, hour, minute, second): self.hour = hour self.minute = minute self.second = second
Let's create a Time
instance and set its attributes:
>>> t = Time() >>> t.set(11, 59, 0) >>> t.hour, t.minute, t.second (11, 59, 0)