Python object-oriented programming, python object-oriented

Source: Internet
Author: User

Python object-oriented programming, python object-oriented
Color

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. The keyword class indicates that we have defined a new class. (Object) In this section, the class Color is an object. The document string describes the function of the Color object, pass indicates that the object is blank (that is, it stores any data and does not provide any new operations ). The usage is as follows:

>>> black = Color()>>> black.red = 00>>> black.green = 00>>> black.blue = 00
Method

According to definition, the color brightness is the maximum and weakest RGB value that corresponds to the value between 0 and 1. If it is written as a function, it is shown 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)    return 0.5 * (strongest + weakest) / 255

If the Functionlightness()As a method of the Color class, it is shown 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)        return 0.5 * (strongest + weakest) / 255

You need to remove the color parameter and replace it with the self parameter. When Python calls a method of an object, it automatically uses the reference of this object as the first parameter of this method. This means that when we call lightness, no parameters need to be passed to it. The usage is as follows:

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

When defining a method, in addition to the parameters that need to be passed in, you must also write one more parameter. On the contrary, when calling a method, the actual provided parameter is less than the one required in the method definition.

Constructor

Add a method to the Color class that will be executed when a new Color is created. This method is called 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 underscores (_) on both sides of the name indicate that this method has special significance for Python-this means that the method will be called when a new object is created.

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

When you need to obtain a simple and easy-to-understand information from an object, _ str __is called. If you need more accurate information, _ repr _ is called __. When print is used, __str _ will be called. To get meaningful output, writeColor.__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)

There are also many special methods in Python: The list completed on the official Python website. There are _ add _, _ sub _, and _ eq _. They are used to add objects with "+", respectively, use "-" to subtract objects and use "=" to compare objects:

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

Specific usage of these methods:

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))

Availablehelp(Color)Obtain help information about the Color class:

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
Summary
  • In object-oriented programming language, the method to define a new type is to create a new class. Classes support encapsulation. In other words, classes put together data and related operations so that other parts of the program can ignore implementation details.
  • Class also supports polymorphism. If the two classes have the same method, their instances can be replaced with each other without affecting other parts of the program. This means that we can implement the plug-and-play programming, that is, the code can execute different operations according to the specific type of processing. (Polymorphism means that an expression containing a variable can get different results based on the actual type of the object referenced by the variable .)
  • The new class can also be defined by "Inheriting existing classes:class child(parent). The system class can not only override the features of the parent class, but also add new features.
  • When a method is defined in a class, its first parameter must be a special variable, which indicates the object that calls the method. By convention, this parameter becomes self.
  • In Python, some methods have special predefined meanings: to make a difference, their names start and end with double underscores. Some of these methods call (_ init _) when constructing an object __), some calls (_ str _ and _ repr _) when converting an object to a string __), some are used to simulate arithmetic operations (such as _ add _ and _ sub __).

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.