This section describes several common classes and methods in Python.

Source: Internet
Author: User

This section describes several common classes and methods in Python.

Built-in method description

_ Init _ (self,...) initialization object, called when creating a new object

_ Del _ (self) releases an object and is called before the object is deleted.

_ New _ (cls, * args, ** kwd) instance generation

_ Str _ (self) is called when the print statement is used.

_ Getitem _ (self, key) obtains the value corresponding to the index key of the sequence, which is equivalent to seq [key].

_ Len _ (self) is called when the inline function len () is called.

_ Cmp _ (stc, dst) compares the src and dst objects.

_ Getattr _ (s, name) Get the attribute value

_ Setattr _ (s, name, value) sets the attribute value

_ Delattr _ (s, name) delete the name attribute

The _ getattribute _ () function is similar to the _ getattr _ () function.

_ Gt _ (self, other) Determine whether the self object is greater than the other object

_ Lt _ (slef, other) determines whether the self object is smaller than the other object

_ Ge _ (slef, other) determines whether the self object is greater than or equal to the other object

_ Le _ (slef, other) determines whether the self object is smaller than or equal to the other object

_ Eq _ (slef, other) Determine whether the self object is equal to the other object

_ Call _ (self, * args) calls an instance object as a function.

_ Init __():

The _ init _ method runs immediately when an object of the class is created. This method can be used to initialize your object. Note that the start and end of the name are double underscores.

Code example:
 

#!/usr/bin/python# Filename: class_init.pyclass Person:  def __init__(self, name):    self.name = name  def sayHi(self):    print 'Hello, my name is', self.namep = Person('Swaroop')p.sayHi()

Output:

Hello, my name is Swaroop

 

Description: __init _ is defined as a parameter name (and a common Parameter self ). In this _ init _, we only create a new domain, also known as name. Note that they are two different variables, even though they have the same name. Point Numbers allow us to differentiate them. The most important thing is that we didn't specifically call the _ init _ method, but when creating a new instance of a class, we included the parameters in parentheses following the class name, to pass the _ init _ method. This is an important part of this method. Now, we can use the self. name field in our method. This is verified in the sayHi method.

_ New __():

_ New _ () is called before _ init _ () to generate instance objects. this method and class attributes can be used to implement the singleton mode in the design mode. is Singleton mode used to create a unique object? A singleton mode class can only instantiate one object.

 

#! /Usr/bin/python #-*-coding: UTF-8-*-class Singleton (object): _ instance = None # define instance def _ init _ (self ): pass def _ new _ (cls, * args, ** kwd): # Call if Singleton before _ init. _ instance is None: # generate a unique Singleton instance. _ instance = object. _ new _ (cls, * args, ** kwd) return Singleton. _ instance

 

 _ Getattr _ (), _ setattr _ (), and _ getattribute __():

When reading an attribute of an object, python automatically calls the _ getattr _ () method. for example, fruit. color will be converted to fruit. _ getattr _ (color ). when the attribute is set using the value assignment statement, python automatically calls the _ setattr _ () method. the function of _ getattribute _ () is similar to that of _ getattr _ (). It is used to obtain the attribute value. however, _ getattribute _ () provides better control and stronger code. note that the _ setattribute _ () method does not exist in python.

Code example:
 

#! /Usr/bin/python #-*-coding: UTF-8-*-class Fruit (object): def _ init _ (self, color = "red ", price = 0): self. _ color = color self. _ price = price def _ getattribute _ (self, name): # return object to obtain the attribute. _ getattribute _ (self, name) def _ setattr _ (self, name, value): self. _ dict _ [name] = value if _ name _ = "_ main _": fruit = Fruit ("blue", 10) print fruit. _ dict __. get ("_ Fruit _ color") # obtain the color attribute fruit. _ dict _ ["_ Fruit _ price"] = 5 print fruit. _ dict __. get ("_ Fruit _ price") # get the price attribute

 

_ Getitem __():

If a class defines an attribute as a sequence, use _ getitem _ () to output an element in the sequence attribute. assume that the fruit shop sells fruit for multiple minutes. You can use the _ getitem _ () method to obtain the unplanted fruit in the fruit shop.

Code example:
 

#! /Usr/bin/python #-*-coding: UTF-8-*-class FruitShop: def _ getitem _ (self, I): # Get fruit return self. fruits [I] if _ name _ = "_ main _": shop = FruitShop () shop. fruits = ["apple", "banana"] print shop [1] for item in shop: # output fruit print item of the fruit shop,

 

Output:

bananaapple banana

 

_ Str __():

_ Str _ () indicates the meaning of an object and returns a string. after the _ str _ () method is implemented, you can directly use the print statement to output the object, or use the str () function to trigger the execution of _ str. in this way, the object and the string are associated to facilitate the implementation of some programs. This string can be used to represent a class.

Code example:
 

#! /Usr/bin/python #-*-coding: UTF-8-*-class Fruit: '''fruit class''' # defines the document string def _ str _ (self) for the Fruit class: # defines the object string to return self. _ doc _ if _ name _ = "_ main _": fruit = Fruit () print str (fruit) # Call the built-in function str () the output result of the Start _ str _ () method is: Fruit class print fruit # directly outputs the object fruit and returns the value of the _ str _ () method. The output result is: fruit class

 

_ Call __():

The _ call _ () method is implemented in the class. when an object is created, the _ call _ () content is directly returned. This method can be used to simulate static methods.

Code example:
 

#! /Usr/bin/python #-*-coding: UTF-8-*-class Fruit: class Growth: # internal class def _ call _ (self ): print "grow... "grow = Growth () # Call Growth (). The Growth class is returned as a function, that is, the method grow () and grow () defined for the external Class Fruit () the code in _ call _ () will be executed if _ name _ = '_ main _': fruit = Fruit () fruit. grow () # output result: grow... fruit. grow () # output result: grow...

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.