定义类的实例

定义类的实例

demo1.py

"""
定义类描述平面上的点
提供移动点
计算一个点到另一个点的距离
"""


class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move_to(self, x, y):
        self.x = x
        self.y = y

    def move_by(self, dx, dy):
        self.x += dx
        self.y += dy

    def distance(self, x, y):
        return ((self.x - x) ** 2 + (self.y - y) ** 2) ** 0.5

    def gap(self, p):
        return ((self.x - p.x) ** 2 + (self.y - p.y) ** 2) ** 0.5

    def __str__(self):
        return f'({
       self.x},{
       self.y})'


if __name__ == '__main__':
    p1 = Point(1, 1)
    p1.move_to(2, 2)
    p2 = Point(3, 4)
    print(p1)
    print(p1.distance(3, 4))
    print(p1.gap(p2))

demo2.py

"""
定义一个线段类
计算线段的长度
判断两条线段是否相交
"""
from demo1 import Point


class Segment:

    def __init__(self, start, end):
        self.start = start
        self.end = end

    def length(self):
        return self.start.gap(self.end)

    def intersected(self, other):
        sx1, sy1, ex1, ey1 = self.start.x, self.start.y, self.end.x, self.end.y
        sx2, sy2, ex2, ey2 = other.start.x, other.start.y, other.end.x, other.end.y
        return not (max(sx1, ex1) < min(sx2, ex2) or
                    max(sx2, ex2) < min(sx1, ex1) or
                    max(sy1, ey1) < min(sy2, ey2) or
                    max(sy2, ey2) < min(sy1, ey1))


if __name__ == '__main__':
    p1 = Point(3, 4)
    p2 = Point(5, 0)
    p3, p4 = Point(5, 6), Point(7, 8)
    s1 = Segment(p1, p2)
    s2 = Segment(p3, p4)
    print(s1.length())
    print(s1.intersected(s2))

创建三角形对象

需要判断三角形是否成立

计算三角形周长和面积

import math


class Triangle:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    @classmethod
    def is_valid_sides(cls, a, b, c):
        return a + b > c and b + c > a and a + c > b

    @staticmethod
    def check_sides(a, b, c):
        return a + b > c and b + c > a and a + c > b

    def perimeter(self):
        return self.a + self.b + self.c

    def area(self):
        p = self.perimeter() / 2
        a, b, c = self.a, self.b, self.c
        return math.sqrt(p * (p - a) * (p - b) * (p - c))


def main():
    a, b, c = map(float, input('请输入三条边的长度: ').split())
    if Triangle.check_sides(a, b, c):
        tri = Triangle(a, b, c)
        print(f'三角形的周长: {
       tri.perimeter()}')
        print(f'三角形的面积: {
       tri.area()}')
    else:
        print('不能构成三角形!')


if __name__ == '__main__':
    main()

扑克牌游戏

import random

SPADE, HEART, CLUB, DIAMOND = range(4)


# 符号常量优于字面常量


class Card:

    def __init__(self, suite, face):
        self.suite = suite
        self.face = face

    def __repr__(self):
        return self.show()

    def __lt__(self, other):
        if self.suite != other.suite:
            return self.suite < other.suite
        face1 = 14 if self.face == 1 else self.face
        face2 = 14 if other.face == 1 else other.face
        return face1 < face2

    def show(self):
        faces = ['', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
        suites = ('♠', '♥', '♣', '♦')
        return f'{
       suites[self.suite]}{
       faces[self.face]}'


class Poker:
    """扑克"""

    def __init__(self):
        self.cards = [Card(suite, face)
                      for suite in range(4)
                      for face in range(1, 14)]
        self.index = 0

    def shuffle(self):
        self.index = 0
        random.shuffle(self.cards)

    def has_more(self):
        return self.index < len(self.cards)

    def deal(self):
        card = self.cards[self.index]
        self.index += 1
        return card


class Player:

    def __init__(self, nickname):
        self.nickname = nickname
        self.cards = []

    def get_card(self, card):
        """摸牌"""
        self.cards.append(card)

    def arrange(self):
        """整理手牌"""
        self.cards.sort()


poker = Poker()
poker.shuffle()
names = ['妲己', '赵云', '韩信', '狄仁杰']
players = [Player(name) for name in names]
for _ in range(13):
    for player in players:
        card = poker.deal()
        player.get_card(card)

for player in players:
    player.arrange()
    print(player.nickname, end=':')
    print(player.cards)

欢迎查看我的技术文档
网站有我的联系方式,欢迎学习交流

你可能感兴趣的