python 类的运用

img


设计一个circle类来表示圆,这个类包含圆的半径以及求面积和周长的函数.

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius
        
    def get_area(self):
        return math.pi * (self.radius ** 2)
    
    def get_perimeter(self):
        return 2 * math.pi * self.radius

my_circle = Circle(3)
print(my_circle.get_area())
print(my_circle.get_perimeter())


class Circle():
  def __init__(self,r):
    self.R = r
  def s(self):
    return PI*(self.R*self.R)
  def l(self):
    return 2*PI*self.R
  • 你看下这篇博客吧, 应该有用👉 :python 面向对象程序设计 1.2 编写程序,定义一个Circle类,根据圆的半径求周长和面积。
  • 除此之外, 这篇博客: 【python教程】-- 入门 | 小甲鱼《零基础入门学Python》教程笔记(知识点详细、源码可复制)全中的 示例 - circle方法绘制圆形 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
    • circle方法绘制圆形
    • circle(Surface, color, pos, radius, width=0)
    • Surface参数:绘制在surface对象上
    • color参数:颜色
    • pos参数:圆心位置
    • radius参数:半径大小
    • width=0:边框大小。0表示填充矩形,1以上表示 使用color指定的颜色绘制边框
    # 跟随鼠标的圆形
    import pygame
    import sys
    from pygame.locals import *
    
    pygame.init()
    
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    GREEN = (0, 255, 0)
    RED = (255, 0, 0)
    BLUE = (0, 0, 255)
    
    size = width, height = 640, 480
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("FishC Demo")
    
    position = size[0] // 2, size[1] // 2
    moving = False
    
    clock = pygame.time.Clock()
    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
    
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    moving = True
    
            if event.type == MOUSEBUTTONUP:
                if event.button == 1:
                    moving = False
    
        if moving:
            position = pygame.mouse.get_pos()
    
        screen.fill(WHITE)
    
        pygame.draw.circle(screen, RED, position, 25, 1)
        pygame.draw.circle(screen, GREEN, position, 75, 1)
        pygame.draw.circle(screen, BLUE, position, 125, 1)
    
        pygame.display.flip()
    
        clock.tick(120)
    

  • 以下回答由chatgpt基于相关博客总结生成:

    解答

    根据参考资料,我们可以针对问题进行如下解答:

    import  math
    
    class Circle:
        def __init__(self, radius):
            self.radius = radius
    
        def get_area(self):
            return round(math.pi * self.radius ** 2, 2)
    
        def get_circumference(self):
            return round(2 * math.pi * self.radius, 2)
    
    # 测试代码
    circle = Circle(4)
    print("圆的面积为:", circle.get_area())
    print("圆的周长为:", circle.get_circumference())
    

    解释:

    • 创建一个 Circle 类,它只有一个属性 radius 表示半径,以及两个方法 get_area()get_circumference() 分别用来求圆的面积和周长。
    • __init__ 方法中初始化类的属性 radius
    • get_area() 方法中,根据圆面积的公式 S=πr^2 计算圆的面积,并返回保留两位小数的结果。
    • get_circumference() 方法中,根据圆周长的公式 C=2πr 计算圆的周长,并返回保留两位小数的结果。
    • 测试代码中,实例化了一个 Circle 对象,并对其调用 get_area()get_circumference() 方法,输出结果。

    最终输出:

    圆的面积为: 50.27
    圆的周长为: 25.13