[Python] object-oriented learning

1. encapsulation, inheritance and polymorphism

  • A set of data structures and the method for processing an object thereof, the object of the same class behavior summarized, by hiding the internal details of a class encapsulation, inheritance and generalization by specialized implementation class of polymorphic Based on the object type of dynamic assignment
  • After we create an object, just to give an object sends a message (call a method) can execute code method, which means that we only need to know the name of the method and the incoming parameters (external view method), and not We need to know (internal view of the method) internal implementation details of the method

2. A good example of object-oriented programming

from time import sleep


class Clock(object):
    """数字时钟"""

    def __init__(self, hour=0, minute=0, second=0):
        """初始化方法

        :param hour: 时
        :param minute: 分
        :param second: 秒
        """
        self._hour = hour
        self._minute = minute
        self._second = second

    def run(self):
        """走字"""
        self._second += 1
        if self._second == 60:
            self._second = 0
            self._minute += 1
            if self._minute == 60:
                self._minute = 0
                self._hour += 1
                if self._hour == 24:
                    self._hour = 0

    def show(self):
        """显示时间"""
        return '%02d:%02d:%02d' % \
               (self._hour, self._minute, self._second)


def main():
    clock = Clock(23, 59, 58)
    while True:
        print(clock.show())
        sleep(1)
        clock.run()


if __name__ == '__main__':
    main()

Guess you like

Origin www.cnblogs.com/bingogo/p/12107738.html