REMEMBER PYTHON

MINTE9
2REMEMBER




Methods

p288 ! Methods are the same as functions but defined inside the class. Invoking a method is different from calling a function.
 RunCode
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

Time.print(start) # 09:45:00
... 8 lines
˄˄˄
p291 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" Sometimes this responsability shift makes the code easier to maintain and reuse.
 RunCode
class Time:
    
    def int_to_time(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))

start = Time()
start.int_to_time(160).print() # 00:02:40
... 11 lines
˄˄˄

Questions    
No. 28   Special Methods
CARD
27
32

        A B C D E F
🔔
1/1