Methods
Methods are the same as functions but defined inside the class.
# Methods are functions defined inside a class
class Time:
def print(self):
print('%.2d:%.2d:%.2d' %
(self.hour, self.minute, self.second)
)
start = Time()
start.hour = 9
start.minute = 45
start.second = 0
# Invoking a method is different from calling a function
Time.print(start) # 09:45:00
Active
In OOP, the objects are the active agents.
# In functional programming, the function is the active agent:
# Hey print_time! Here's an object to print
#
# In OOP, the objects are the active agents.
# Hey obj start! Please print yourself
class Time:
def set(self, seconds):
time = Time()
minutes, time.seconds = divmod(seconds, 60)
hour, time.minutes = divmod(minutes, 60)
time.hour = hour
return time
def print(self):
print('%.2d:%.2d:%.2d' %
(self.hour, self.minutes, self.seconds)
)
time = Time()
time.set(160).print() # 00:02:40
Special methods
Method __init__ gets invoked when an object is instantiated.
# Method __init__ gets invoked when an object is instantiated
# Method __str__ returns a string representation of an object
class Time:
def __init__(self, hour=0, min=0, sec=0):
self.hour = hour
self.min = min
self.sec = sec
def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.min, self.sec)
time = Time(9, 30)
print(time) # 09:30:00
Last update: 346 days ago