Python: clock class to describe the class's constructor (the init) hidden attribute, the attribute disclosed

"""
面向对象有三大支柱:封装、继承和多态。
封装:隐藏实现细节,只向外界提供接口
类中定义的方法就是把数据和对数据的操作封装起来
创建之后,给对象发消息(调用对象的方法)就可以执行方法中的代码
也就是说我们只需要知道方法名和传入什么参数
无需知道方法内部实现细节
"""
import time


# 定义一个类描述时钟
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
        # 可访问
        self.can_see = '你能看到我!'

    # 走字
    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 str_time(self):
        return '%2d:%2d:%2d' % (self.__hour, self.__minute, self.__second)


def main():
    clock = Clock(1, 1, 1)
    # print(clock.__hour) 'Clock' object has no attribute '__hour' 隐藏了
    print(clock.can_see)
    while True:
        print(clock.str_time())
        time.sleep(1)
        clock.run()


if __name__ == '__main__':
    main()

 

The effect is as:

 

Published 52 original articles · won praise 34 · views 2612

Guess you like

Origin blog.csdn.net/weixin_38114487/article/details/103932912