0

这是我的总体说明

编写一个使用 0 到 255 范围内的整数值表示 RGB 颜色的 Color 类。您的类必须: 放在 image.py 中 提供一个构造函数,该构造函数接受来自客户端的红色、绿色和蓝色通道的值并存储这些值提供返回红色、绿色和蓝色通道值的公共方法

编写一个表示 PPM 图像的 PortablePixmap 类。您的类必须: 放置在 image.py 中 提供一个构造函数,该构造函数接受来自客户端的幻数、宽度、高度、最大颜色值和像素数据并存储这些值 将像素数据存储为列表(或列表列表) of) 颜色对象 提供一个公共方法,该方法返回 PPM 图像的字符串表示形式

编写一个 read_ppm 函数,该函数打开一个 PPM 图像文件,读取其内容,并返回一个包含其内容的 PortablePixmap 对象。您的函数必须: 放在 image.py 中 读取 PPM 图像文件的内容 对 PPM 图像文件的格式不敏感 如果预期像素数和提供的像素数不同,则退出并出错

编写一个测试您的 read_ppm 函数的主函数。你的函数必须放在 main.py

这就是我迄今为止所拥有的

class Color:
# constructor takes in values from client and stores them
def __init__(self, red, green, blue): 


    # checks that type of arg == int: raises exception otherwise 
    if (isinstance(red, int) and isinstance(green, int) and isinstance(blue, int)):     
        print("good stuff, indeed integers")
    else:   
        raise TypeError("Argument must be an integer.")

    # checks if values are between 0 and 225 
    if red < 0 or red > 225: 
        print("0 < rgb values < 225")
    elif green < 0 or green > 225:
        print("0 < rgb values < 225") 
    elif blue < 0 or blue > 225:
        print("0 < rgb values < 225")

    # instance variables (RGB values)
    self._red = red 
    self._green = green
    self._blue = blue 


# methods that reuturn RGB values
def returnRed(self): 
    return self._red 

def returnGreen(self):
    return self._green

def returnBlue(self):
    return self._blue


'''class that represents a PPM image'''
class PortablePixmap:
    def __init__(self, magic_number, width, height, max_color_value, pixel_data):
        self._magic_number = magic_number
        self._width = width
        self._height = height
        self._max_color_value = max_color_value
        self._pixel_data = pixel_data


    def __str__(self):
        s = self._magic_number
        s += '\n' + str(self._width)
        s += ' ' + str(self._height)
        s += '\n' + str(self._max_color_value)
        for pixel in self._pixel_data:
            s += ' ' + str(pixel[0])
            s += ' ' + str(pixel[1])
            s += ' ' + str(pixel[2])

        return s

我有几个问题需要澄清。 1. 我是否正确地创建了 Color 类?2. 我什至需要专门在该类中提出任何异常?我们最终将从一个包含所有内容的文件中读取,但不一定在它自己的单独行上。

我真的只是想知道我是否正确地处理了这个问题。这些说明似乎是逐步进行的,但我并不真正了解一切是如何联系起来的,所以我担心我做的太多或太少。

提前致谢

4

1 回答 1

0

从规范中不清楚您需要检查值,并且您的检查仅在某些情况下引发异常,否则会导致副作用(打印);从重用的角度来看,如果有的话,我宁愿只有例外。除了缩进错误(我假设它只是在这里,而不是在你的源代码中)之外,Color 类看起来可以满足需求,尽管它们对于访问器来说是非常不符合标准的;可能有人受过Java培训。

文档字符串应该在 PortablePixmap 类中,而不是在它之上。

最引人注目的是您的班级对 PPM 格式不敏感并将像素存储为 8 位无符号 RGB 的要求的组合。这使得支持所有 PPM 成为不可能,因为它们支持 16 位值(注意PPM 格式中的 maxval 字段)。

您的 PortablePixmap 类也不使用 Color 类:“将像素数据存储为 Color 对象列表(或列表列表)”。这个要求迫使实施效率非常低,但我想整个事情都是一个练习。您需要从像素数据字符串中提取 RGB 三元组。这也是您需要指定的一项检查的地方;验证是否有正确数量的像素。如果失败,人们会期望 ValueError 异常。

如果我正在编写这种东西,我可能会使用插槽来减少诸如 Color 之类的类的内存使用,使用数组来处理大量有限范围的数值,并可能使用属性来使存储透明,而无需使用笨拙的 getter 方法。splitjoin将使处理像素集合变得更容易。

于 2014-04-05T14:03:18.713 回答