Python-Day05-面向对象编程基础

Author: Seven_0507
Date: 2019-05-20

Day05主要重新学习总结Python面向对象编程的基础知识!
在这里插入图片描述

Python面向对象编程习题

1. 创建使用类和对象

"""
定义和使用学生类
实例化学生类,使用对象
"""
class Student(object):
    """学生类"""

    # __init__是一个特殊方法用于在创建对象时进行初始化操作
    # 通过这个方法可以为学生对象绑定name和age两个属性
    def __init__(self, name, age):
        """初始化方法"""
        self.name = name
        self.age = age

    def study(self, course_name):
        """定义学习方法"""
        print('%s正在学习%s.' % (self.name, course_name))

    # PEP 8要求标识符的名字用全小写多个单词用下划线连接
    # 但是很多程序员和公司更倾向于使用驼峰命名法(驼峰标识)
    def watch_tv(self):
        """定义看电视方法"""
        if self.age < 18:
            print('%s只能观看《熊出没》.' % self.name)
        else:
            print('%s正在观看爱国主义教育.' % self.name)


def main():
    # 实例化Student类为stu1
    stu1 = Student('五月猴', 27)
    # 调用study、watch_tv方法
    stu1.study('Python程序设计')
    stu1.watch_tv()
    print('-'*50)
    
    # 实例化Student类为stu2
    stu2 = Student('王大锤', 15)
    stu2.study('思想品德')
    stu2.watch_tv()

if __name__ == '__main__':
    main()
五月猴正在学习Python程序设计.
五月猴正在观看爱国主义教育.
--------------------------------------------------
王大锤正在学习思想品德.
王大锤只能观看《熊出没》.
"""
属性访问限制
"""
class Test:

    def __init__(self, foo):
        """
        初始化方法
        属性命名时用两个下划线作为开头设置为私有,__foo
        """
        self.__foo = foo

        
    def __bar(self):
        print(self.__foo)
        print('__bar')


def main():
    # 类的实例化
    test = Test('hello')
    # test.__bar() # 报错,无法访问私有变量
    # 访问私有属性的方法
    test._Test__bar()
    print(test._Test__foo)


if __name__ == "__main__":
    main()
hello
__bar
hello

2. 定义数字时钟类

"""
定义和使用时钟类
"""

import time
import os


class Clock(object):
    """数字时钟"""
    # Python中的函数是没有重载的概念的
    # 因为Python中函数的参数没有类型而且支持缺省参数和可变参数
    # 用关键字参数让构造器可以传入任意多个参数来实现其他语言中的构造器重载
    def __init__(self, **kw):
        """初始化方法"""
        if 'hour' in kw and 'minute' in kw and 'second' in kw:
            self._hour = kw['hour']
            self._minute = kw['minute']
            self._second = kw['second']
        else:
            tm = time.localtime(time.time())
            self._hour = tm.tm_hour
            self._minute = tm.tm_min
            self._second = tm.tm_sec

    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)


if __name__ == '__main__':
    # clock = Clock(hour=10, minute=5, second=58)
    # Clock实例化操作
    clock = Clock()
    count = 0
    while True:
        os.system('clear')
        print(clock.show())
        time.sleep(1) #休眠1s
        clock.run()
        count+=1
        if count==6:
            break
22:57:54
22:57:55
22:57:56
22:57:57
22:57:58
22:57:59

3. 定义图形类

"""
定义和使用矩形类
"""

class Rect(object):
    """定义矩形类"""

    def __init__(self, width=0, height=0):
        """初始化方法"""
        self.__width = width
        self.__height = height

    def perimeter(self):
        """计算周长方法"""
        return (self.__width + self.__height) * 2

    def area(self):
        """计算面积方法"""
        return self.__width * self.__height

    def __str__(self):
        """矩形对象的字符串表达式"""
        return '矩形[%f,%f]' % (self.__width, self.__height)

    def __del__(self):
        """析构器"""
        print('销毁矩形对象')


if __name__ == '__main__':
    # Rect类的实例化为对象rect1
    rect1 = Rect()
    print(rect1)
    print(rect1.perimeter())
    print(rect1.area())
    print('-'*50)
    
    # Rect类的实例化为对象rect2
    rect2 = Rect(3.5, 4.5)
    print(rect2)
    print(rect2.perimeter())
    print(rect2.area())
矩形[0.000000,0.000000]
0
0
--------------------------------------------------
矩形[3.500000,4.500000]
16.0
15.75

4. 猜数字游戏

"""
面向对象版本的猜数字游戏
"""
from random import randint


class GuessMachine(object):
    """定义猜数字游戏类"""

    def __init__(self):
        """初始化方法"""
        self._answer = None
        self._counter = None
        self._hint = None

    def reset(self):
        """定义生成随机数的方法"""
        self._answer = randint(1, 100)
        self._counter = 0
        self._hint = None

    def guess(self, your_answer):
        """定义猜数字方法"""
        self._counter += 1
        if your_answer > self._answer:
            self._hint = '小一点'
        elif your_answer < self._answer:
            self._hint = '大一点'
        else:
            self._hint = '恭喜你猜对了'
            return True
        return False

    @property # 装饰器就是负责把一个方法变成属性调用
    def counter(self):
        return self._counter

    @property
    def hint(self):
        return self._hint


if __name__ == '__main__':
    # 实例化
    gm = GuessMachine()
    play_again = True
    # while循环实现
    while play_again:
        game_over = False
        # 调用类的reset方法
        gm.reset()
        while not game_over:
            your_answer = int(input('请输入: '))
            # 调用类的guess方法
            game_over = gm.guess(your_answer)
            print(gm.hint)
        if gm.counter > 7:
            print('智商余额不足!')
        play_again = input('再玩一次?(yes|no)') == 'yes'
请输入: 50
大一点
请输入: 80
小一点
请输入: 70
小一点
请输入: 60
小一点
请输入: 56
大一点
请输入: 58
小一点
请输入: 57
恭喜你猜对了
再玩一次?(yes|no)NO

5. 定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法

from math import sqrt


class Point(object):
    """定义类Point"""

    def __init__(self, x=0, y=0):
        """初始化方法
        :param x: 横坐标
        :param y: 纵坐标
        """
        self.x = x
        self.y = y

    def move_to(self, x, y):
        """移动到指定位置
        :param x: 新的横坐标
        "param y: 新的纵坐标
        """
        self.x = x
        self.y = y

    def move_by(self, dx, dy):
        """移动指定的增量
        :param dx: 横坐标的增量
        "param dy: 纵坐标的增量
        """
        self.x += dx
        self.y += dy

    def distance_to(self, other):
        """计算与另一个点的距离
        :param other: 另一个点
        """
        dx = self.x - other.x
        dy = self.y - other.y
        return sqrt(dx ** 2 + dy ** 2)

    def __str__(self):
        return '(%s, %s)' % (str(self.x), str(self.y))


def main():
    # 实例化类Point
    p1 = Point(3, 5)
    p2 = Point()
    print(p1)
    print(p2)
    print('-'*50)
    
    p2.move_by(-1, 2)
    print(p2)
    print(p1.distance_to(p2))


if __name__ == '__main__':
    main()
(3, 5)
(0, 0)
--------------------------------------------------
(-1, 2)
5.0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值