Python面向对象编程

Color类

从一个非常简单的类定义开始:

class Color(object):
    ‘‘‘An RGB color,with red,green,blue component‘‘‘

    pass

关键字def用于告诉Python我们定义了一个新函数,关键字class则表明我们定义了一个新类。(object)这部分内容说的是,类Color是一种对象;文档字符串描述了Color对象的功能,pass则说明该对象是空白的(即为存放任何数据,也没有提供任何的新操作)。使用方式如下:

>>> black = Color()
>>> black.red = 0
0
>>> black.green = 0
0
>>> black.blue = 0
0

方法

根据定义,颜色亮度就是其最强和最弱的RGB值得平均值对应到0和1之间的那个数值。若写成函数,如下所示:

def lightness(color):
    ‘‘‘Return the lightness of color.‘‘‘

    strongest = max(color.red, color.green, color.blue)
    weakest = min(color.red, color.green, color.blue)
    return 0.5 * (strongest + weakest) / 255

若将函数lightness()作为Color类的一个方法,如下所示:

class Color(object):
    ‘‘‘An RGB color,with red,green,blue component‘‘‘

    def lightness(self):
        ‘‘‘Return the lightness of color.‘‘‘

        strongest = max(self.red, self.green, self.blue)
        weakest = min(self.red, self.green, self.blue)
        return 0.5 * (strongest + weakest) / 255

需要移除参数color,并将其替换成self参数。当Python在调用某个对象中的某个方法时,会自动将该对象的引用作为该方法的第一个参数传进去。这就意味着,当我们调用lightness时,完全不需要给它传递任何参数。使用方式如下:

>>> purple = Color()
>>> purple.red = 255
>>> purple.green = 0
>>> purple.blue = 255
>>> purple.lightness()
0.5

定义一个方法的时候,除了实际需要传入的那些参数之外,还必须再多写一个。相反,在调用某个方法的时候,实际提供的参数要比该方法定义中所需的少一个。

构造器

给Color类添加一个当创建新Color的时候就会被执行的方法。这种方法叫做构造器(constructor);在Python中,构造器就是__init__:

class Color(object):
    ‘‘‘An RGB color,with red,green,blue component‘‘‘

    def __init__(self, r, g, b):
        ‘‘‘A new color with red value r, green value g, and blue value b. All
        components are integers in the range 0-255.‘‘‘
        self.red = r
        self.green = g
        self.blue = b

名称两边的双下划线说明该方法对Python有着特殊的意义——这里的意思就是说,创建新对象的时候,该方法就会被调用。

purple = Color(128, 0, 128)

特殊方法

当需要从某个对象得到一段简单易懂的信息时,就会调用__str__;当需要这段信息更准确时,则会调用__repr__。在使用print时,__str__就会被调用。为了得到有意义的输出,现在来写个Color.__str__:

class Color(object):
    ‘‘‘An RGB color,with red,green,blue component‘‘‘

    def __init__(self, r, g, b):
        ‘‘‘A new color with red value r, green value g, and blue value b. All
        components are integers in the range 0-255.‘‘‘
        self.red = r
        self.green = g
        self.blue = b

    def __str__(self):
        ‘‘‘Return a string representation of this Color in the form of an RGB tuple.‘‘‘

        return‘(%s, %s, %s)‘ %(self.red, self.green, self.blue)

Python中还有很多特殊方法:Python的官方网站上给出了完成的列表。其中就有__add__、__sub__、__eq__等,它们分别在我们用“+”对对象做加法,用“-”对对象做减法、用“==”对对象做比较的时候调用:

class Color(object):
    ‘‘‘An RGB color,with red,green,blue component‘‘‘

    def __init__(self, r, g, b):
        ‘‘‘A new color with red value r, green value g, and blue value b. All
        components are integers in the range 0-255.‘‘‘
        self.red = r
        self.green = g
        self.blue = b

    def __str__(self):
        ‘‘‘Return a string representation of this Color in the form of an RGB tuple.‘‘‘

        return‘(%s, %s, %s)‘ %(self.red, self.green, self.blue)

    def __add__(self, other_color):
        ‘‘‘Return a new Color made from adding the red, green and blue components
        of this Color to Color other_color‘s components. If the sum is greater than
        255, the color is set to 255‘‘‘

        return Color(min(self.red + other_color.red, 255),
                     min(self.green + other_color.green, 255),
                     min(self.blue + other_color.blue, 255))

    def __sub__(self, other_color):
        ‘‘‘Return a new Color made from subtracting the red, green and blue components
        of this Color to Color other_color‘s components. If the difference is less than 
        255, the color is set to 0‘‘‘

        return Color(min(self.red - other_color.red, 0),
                     min(self.green - other_color.green, 0),
                     min(self.blue - other_color.blue, 0))

    def __eq__(self, other_color):
        ‘‘‘Return True if this Color‘s components are equal to Color other_color‘s components.‘‘‘

        return self.red == other_color.red and self.green == other_color.green             and self.blue == other_color.blue

    def lightness(self):
        ‘‘‘Return the lightness of color.‘‘‘
        strongest = max(self.red, self.green, self.blue)
        weakest = min(self.red, self.green, self.blue)
        return 0.5 * (strongest + weakest) / 255

这些方法的具体用法:

purple = Color(128, 0, 128)
white = Color(255, 255, 255)
dark_grey = Color(50, 50, 50)
print(purple + dark_grey)
print(white - dark_grey)
print(white == Color(255, 255, 255))

可以使用help(Color)获取有关Color类的帮助信息:

Help on Color in module __main__ object:

class Color(builtins.object)
 |  An RGB color,with red,green,blue component
 |  
 |  Methods defined here:
 |  
 |  __add__(self, other_color)
 |      Return a new Color made from adding the red, green and blue components
 |      of this Color to Color other_color‘s components. If the sum is greater than
 |      255, the color is set to 255
 |  
 |  __eq__(self, other_color)
 |      Return True if this Color‘s components are equal to Color other_color‘s components.
 |  
 |  __init__(self, r, g, b)
 |      A new color with red value r, green value g, and blue value b. All
 |      components are integers in the range 0-255.
 |  
 |  __str__(self)
 |      Return a string representation of this Color in the form of an RGB tuple.
 |  
 |  __sub__(self, other_color)
 |      Return a new Color made from subtracting the red, green and blue components
 |      of this Color to Color other_color‘s components. If the difference is less than 
 |      255, the color is set to 0
 |  
 |  lightness(self)
 |      Return the lightness of color.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。