Python Object-oriented programming

Source: Internet
Author: User

Color class

Start with a very simple class definition:

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

The keyword DEF is used to tell Python that we have defined a new function, and the keyword class indicates that we have defined a new class. This part of the content says that the class color is an object, the document string describes the function of the color object, and pass indicates that the object is blank (that is, to hold any data, and no new actions are provided). Use the following methods:

>>> black = Color()>>> 00>>> 00>>> 00
Method

By definition, the color luminance is the value of its strongest and weakest RGB values corresponding to 0 and 1. If the function is written as follows:

def lightness(color):    ‘‘‘Return the lightness of color.‘‘‘    strongest = max(color.red, color.green, color.blue)    weakest = min(color.red, color.green, color.blue)    return0.5255

If you use lightness() a function as a method of the color class, as follows:

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)        return0.5255

The parameter color needs to be removed and replaced with the self parameter. When Python invokes a method in an object, it automatically passes the object's reference as the first argument to the method. This means that when we call lightness, there is absolutely no need to pass any arguments to it. Use the following methods:

>>> purple = Color()>>> 255>>> 0>>> 255>>> purple.lightness()0.5

When defining a method, you must write one more than the parameters that actually need to be passed in. Conversely, when a method is called, the actual supplied parameter is less than what is required in the method definition.

Constructors

Add a method to the color class that will be executed when a new color is created. This method is called the constructor (constructor); In Python, the constructor is __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

The double underline on both sides of the name indicates that the method has a special meaning for python-meaning that the method is called when a new object is created.

purple = Color(128, 0, 128)
Special methods

__str__ is called when a simple piece of information needs to be obtained from an object, and __repr__ is called when this information is more accurate. When you use print, the __str__ is called. To get a meaningful output, now write a 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 is 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)

There are many special methods in Python: The complete list is given on the official Python website. Among them are __add__, __sub__, __eq__, and so on, they respectively in we use "+" to add to the object, with "-" to do subtraction of the object, with "= =" to compare the object when the call:

 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 is 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 was set to 255 "        returnColor (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_col or ' s components. If the difference is less than 255, the color was set to 0 "        returnColor (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 is equal to color other_color ' s components.        returnself.red = = other_color.red andSelf.green = = Other_color.green andSelf.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

Specific uses of these methods:

Color(1280128Color(255255255Color(505050Color(255255255))

You can use help(Color) the Get help information about the color class:

Help onColorinchModule __main__ object:classColor (Builtins.object) | An RGB color, withRed,green,blue Component |  |   Methods defined here: |  |      __add__ (self, other_color) | Return a new Color made fromAdding theRed, Green andBlue Components | ofThis Color toColor Other_color ' s components. If theSum is Greater than|255, theColor is Set  to 255|  |      __eq__ (self, other_color) | Return TrueifThis Color ' s components isEqual  toColor Other_color ' s components.   |  |      __init__ (self, r, G, b) | A New Color withRed value R, Green value G, andBlue value B.      All | Components is integersinch  theRange0-255.|  |      __str__ (self) | Return AstringRepresentation ofThis Colorinch  theForm ofAn RGB tuple.   |  |      __sub__ (self, other_color) | Return a new Color made fromSubtracting theRed, Green andBlue Components | ofThis Color toColor Other_color ' s components. If theDifference is Less than|255, theColor is Set  to 0|  |      Lightness (self) | Return theLightness ofColor.   | |----------------------------------------------------------------------|   Data descriptors defined here: |  |      __dict__ | Dictionary forInstance variables (ifDefined) |  | __weakref__ |List  ofWeak references to  theObject (ifDefined) | |----------------------------------------------------------------------| Data andOther attributes defined here: |  | __hash__ = None

Python Object-oriented programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.