Time
Class with Properties for Data Access¶Time
¶Before we look at class Time
’s definition, let’s demonstrate its capabilities
from timewithproperties import Time
Time
Object¶Time
objectTime
’s __init__
method has hour
, minute
and second
parameters, each with a default argument value of 0wake_up = Time(hour=6, minute=30)
Time
Object¶Time
defines two methods that produce string representations of Time
object__repr__
special method to produce a string representation of the objectwake_up
__str__
special method is called when an object is converted to a string, such as when you output the object with print
print(wake_up)
Time
provides hour
, minute
and second
propertieswake_up.hour
hour
data attribute’s valuehour
method that returns the value of an _hour
data attributeTime
¶Time
method set_time
method provides hour
, minute
and second
parameters, each with a default of 0
wake_up.set_time(hour=7, minute=45)
wake_up
Time
also supports setting the hour
, minute
and second
values individually via its propertieswake_up.hour = 6
wake_up
hour
method that takes 6
as an argument, validates the value, then assigns it to a corresponding data attribute named _hour
To prove that class Time
’s properties validate the values you assign to them, let’s try to assign an invalid value to the hour
property, which results in a ValueError
:
wake_up.hour = 100
©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.